💾

Redis

9 notes  •  Databases

Redis CLI Commands Quick Reference

Frequently used Redis commands for managing data structures, persistence, and server administration.

Key Operations

SET key value           # Set a key
GET key                 # Get a value
DEL key [key ...]       # Delete one or more keys
EXISTS key              # Check if key exists (1=yes, 0=no)
EXPIRE key seconds      # Set TTL on a key
TTL key                 # Get remaining TTL
KEYS pattern            # Find keys matching pattern (use SCAN in production)
SCAN 0 MATCH prefix:*   # Iterate keys safely

Strings

SET counter 0
INCR counter
INCRBY counter 5
APPEND key value

Lists

LPUSH mylist value      # Push to head
RPUSH mylist value      # Push to tail
LPOP mylist             # Pop from head
LRANGE mylist 0 -1      # Get all elements
BLPOP mylist timeout    # Blocking pop

Hashes

HSET user:1 name "Ravi" email "r@example.com"
HGET user:1 name
HGETALL user:1
HDEL user:1 email

Sets

SADD myset member1 member2
SMEMBERS myset
SISMEMBER myset member1
SREM myset member1

Server

INFO                    # Server statistics
DBSIZE                  # Number of keys in current DB
SELECT 1                # Switch to database 1
BGSAVE                  # Trigger background save
SHUTDOWN SAVE           # Save and shut down
FLUSHDB                 # Delete all keys in current DB
FLUSHALL                # Delete all keys in all DBs

Clear the Redis Database

Use FLUSHDB to clear the current Redis database, or FLUSHALL to clear all databases.

Check Redis Version

redis-server --version

Flush the Current (Default) Database

redis-cli FLUSHDB

Flush a Specific Database by Number

# Flush database number 8
redis-cli -n 8 FLUSHDB

Flush ALL Databases

redis-cli FLUSHALL

Async Flush (Redis 4.0+, non-blocking)

redis-cli FLUSHALL ASYNC

Notes

  • These operations are irreversible. Always confirm you are targeting the correct database.
  • In production, consider enabling RDB or AOF persistence before flushing to allow recovery.

Install Redis on Amazon EC2 (Amazon Linux / CentOS)

Install Redis from the EPEL repository on Amazon Linux or CentOS and configure it as a system service.

Option 1 - Install from EPEL (Recommended)

# Amazon Linux 2 / CentOS 7
sudo amazon-linux-extras install redis6 -y
# or
sudo yum install -y redis

Option 2 - Compile from Source

sudo yum install -y gcc make
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
sudo make install

Start and Enable Redis

sudo systemctl start redis
sudo systemctl enable redis

Basic Security Config

Edit /etc/redis/redis.conf:

bind 127.0.0.1          # Only listen locally
requirepass StrongPass  # Set a password
protected-mode yes
sudo systemctl restart redis

Verify

redis-cli ping   # Should return PONG

Uninstall Redis Server from Ubuntu

Remove Redis from Ubuntu, whether it was installed via apt or compiled from source.

If Installed via apt

# Remove Redis and auto-remove unused dependencies
sudo apt-get purge --auto-remove redis-server redis-tools

If Installed from Source (make install)

Source builds do not have an uninstall target. Remove the files manually:

# Stop the service
sudo systemctl stop redis
sudo systemctl disable redis

# Remove binaries (installed to /usr/local/bin by default)
sudo rm -f /usr/local/bin/redis-server
sudo rm -f /usr/local/bin/redis-cli
sudo rm -f /usr/local/bin/redis-benchmark

# Remove config and data
sudo rm -rf /etc/redis
sudo rm -f /var/lib/redis/dump.rdb

# Remove the systemd service file
sudo rm -f /etc/systemd/system/redis.service
sudo systemctl daemon-reload

Verify Removal

which redis-server   # Should return nothing
redis-cli ping       # Should fail (command not found)

Use Redis as Cache Backend and Session Storage in Magento

Configure Magento to use Redis for the cache backend and session storage, replacing the default file-based cache for better performance and scalability.

Prerequisites

  • Redis installed and running (same or separate server)
  • Magento 2.x
  • predis/predis or phpredis extension installed

Configure Cache Backend

Run the Magento CLI command:

php bin/magento setup:config:set \
    --cache-backend=redis \
    --cache-backend-redis-server=127.0.0.1 \
    --cache-backend-redis-db=0 \
    --cache-backend-redis-port=6379

Configure Session Storage

php bin/magento setup:config:set \
    --session-save=redis \
    --session-save-redis-host=127.0.0.1 \
    --session-save-redis-port=6379 \
    --session-save-redis-db=2 \
    --session-save-redis-max-concurrency=20

Verify Configuration

Check app/etc/env.php to confirm the Redis settings were saved. Then flush cache and test:

php bin/magento cache:flush
redis-cli -n 0 DBSIZE   # Should show cache keys

Back Up and Restore Redis Data

Back up Redis data using RDB snapshots and restore them on the same or a different server.

Step 1 - Find the Data Directory

redis-cli CONFIG GET dir
redis-cli CONFIG GET dbfilename

The dump file is typically /var/lib/redis/dump.rdb.

Step 2 - Create a Fresh Backup

# Trigger a synchronous save
redis-cli BGSAVE

# Wait for it to complete
redis-cli LASTSAVE   # returns Unix timestamp of last save

Step 3 - Copy the Dump File

sudo cp /var/lib/redis/dump.rdb /backup/redis-dump-$(date +%Y%m%d).rdb

Restore on the Same or Another Server

  1. Stop Redis: sudo systemctl stop redis
  2. Copy the dump: sudo cp /backup/redis-dump.rdb /var/lib/redis/dump.rdb
  3. Fix permissions: sudo chown redis:redis /var/lib/redis/dump.rdb
  4. Start Redis: sudo systemctl start redis

Automate with Cron

# Daily backup at 2 AM
0 2 * * * redis-cli BGSAVE && cp /var/lib/redis/dump.rdb /backup/redis-$(date +\%Y\%m\%d).rdb

Notes

  • The restore server must run a Redis version equal to or newer than the source.

Open Redis Port for Remote Connections

By default, Redis only listens on 127.0.0.1:6379. To allow remote connections, update the Redis config and open the firewall port.

Step 1 - Configure Redis to Listen Remotely

Edit /etc/redis/redis.conf:

# Change from:
bind 127.0.0.1

# To (specify your server IP or 0.0.0.0 for all interfaces):
bind 0.0.0.0

# Always set a password when enabling remote access:
requirepass YourStrongPassword
sudo systemctl restart redis

Step 2 - Open Firewall Port

# UFW
sudo ufw allow from CLIENT_IP to any port 6379

# iptables
sudo iptables -A INPUT -s CLIENT_IP -p tcp --dport 6379 -j ACCEPT

Verify

# Check Redis is listening
ss -tlnp | grep 6379

# Test remote connection
redis-cli -h SERVER_IP -p 6379 -a YourStrongPassword ping

Notes

  • Never expose Redis to the public internet without authentication and strict firewall rules. Unauthenticated Redis instances are a common attack target.

Flush Redis Cache and Delete All Keys

Delete keys from a Redis database using the FLUSHDB or FLUSHALL commands.

Commands

# Delete all keys in the currently selected database
redis-cli FLUSHDB

# Delete all keys in ALL databases
redis-cli FLUSHALL

# Non-blocking flush (Redis 4.0+, runs in background)
redis-cli FLUSHALL ASYNC

Flush a Specific Database

# Select database 1 and flush it
redis-cli -n 1 FLUSHDB

Delete Keys Matching a Pattern (Safer)

# Use SCAN + DEL instead of KEYS in production
redis-cli --scan --pattern "cache:*" | xargs redis-cli DEL

Notes

  • FLUSHDB/FLUSHALL are irreversible. Ensure RDB/AOF persistence is configured before running them in production.
  • Prefer pattern-based deletion over full flush when only specific keys need to be removed.

Move a Redis Database to Another Server

Migrate a Redis database to a new server by copying the RDB dump file.

Step 1 - Save the Dump on Server A

redis-cli CONFIG GET dir    # Find the data directory (e.g. /var/lib/redis)
redis-cli SAVE             # Force synchronous save

Step 2 - Copy dump.rdb to Server B

scp /var/lib/redis/dump.rdb user@SERVER_B:/tmp/dump.rdb

Step 3 - Restore on Server B

sudo systemctl stop redis
sudo cp /tmp/dump.rdb /var/lib/redis/dump.rdb
sudo chown redis:redis /var/lib/redis/dump.rdb
sudo systemctl start redis

Verify

redis-cli DBSIZE    # Should match the original server key count
redis-cli KEYS "*" | head -20

Alternative - Use redis-cli --pipe or MIGRATE Command

# Migrate a single key from A to B
redis-cli MIGRATE SERVER_B_IP 6379 mykey 0 5000

Notes

  • Server B must run the same or a newer version of Redis as Server A.
  • For live migration with minimal downtime, consider setting up replication temporarily.