Redis

Installation

Ubuntu/Debian

# Update package manager
sudo apt update
 
# Install Redis
sudo apt install redis-server -y
 
# Verify installation
redis-cli --version
redis-server --version
 
# Start and enable Redis
sudo systemctl start redis-server
sudo systemctl enable redis-server
 
# Check status
sudo systemctl status redis-server

CentOS/RHEL

# Install Redis
sudo yum install redis -y
 
# Start and enable Redis
sudo systemctl start redis
sudo systemctl enable redis
 
# Check status
sudo systemctl status redis
 
# Verify installation
redis-cli --version
# Pull Redis image
docker pull redis:latest
 
# Run Redis container
docker run -d \
  --name redis \
  -p 6379:6379 \
  -v redis-data:/data \
  redis:latest redis-server --appendonly yes
 
# Or with custom port
docker run -d \
  --name redis \
  -p 6380:6379 \
  -v redis-data:/data \
  redis:latest

Docker Compose

version: '3.8'
 
services:
  redis:
    image: redis:latest
    container_name: redis
    restart: always
    ports:
      - "6379:6379"
    volumes:
      - redis-data:/data
    command: redis-server --appendonly yes
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
 
volumes:
  redis-data:

Service Management

# Start Redis
sudo systemctl start redis-server
 
# Stop Redis
sudo systemctl stop redis-server
 
# Restart Redis
sudo systemctl restart redis-server
 
# Check status
sudo systemctl status redis-server
 
# View logs
sudo tail -f /var/log/redis/redis-server.log

Configuration

Edit Redis Configuration

# Main configuration file
sudo nano /etc/redis/redis.conf

Important Settings

# Port
port 6379

# Bind address (allow remote connections)
bind 0.0.0.0
# Or specific IP
bind 127.0.0.1 192.168.1.100

# Password (set for security)
requirepass your_password

# Max memory
maxmemory 256mb

# Memory eviction policy
maxmemory-policy allkeys-lru

# Persistence - RDB (snapshot)
save 900 1           # Save after 900 sec if 1 key changed
save 300 10          # Save after 300 sec if 10 keys changed
save 60 10000        # Save after 60 sec if 10000 keys changed

# Persistence - AOF (append-only file)
appendonly yes
appendfsync everysec

# Logging
loglevel notice
logfile /var/log/redis/redis-server.log

# Database
databases 16

# Timeout
timeout 0
tcp-keepalive 300

Apply Configuration Changes

# Restart Redis to apply changes
sudo systemctl restart redis-server
 
# Verify configuration
redis-cli CONFIG GET port
redis-cli CONFIG GET requirepass

Connect to Redis

CLI Connection

# Connect to local Redis
redis-cli
 
# Connect to remote Redis
redis-cli -h hostname -p 6379
 
# Connect with password
redis-cli -h hostname -p 6379 -a password
 
# Connect to specific database
redis-cli -n 1   # Connect to database 1

Test Connection

# Test with PING
redis-cli ping
 
# Test with custom message
redis-cli ECHO "Hello Redis"

Basic Commands

String Operations

# Set key
SET key "value"
 
# Get key
GET key
 
# Check key exists
EXISTS key
 
# Delete key
DEL key
 
# Append value
APPEND key "more"
 
# Get length
STRLEN key
 
# Set with expiration (seconds)
SET key "value" EX 3600
 
# Get remaining TTL
TTL key
 
# Set expiration
EXPIRE key 3600
 
# Remove expiration
PERSIST key

List Operations

# Push to list
LPUSH mylist "a" "b" "c"    # Push to left
RPUSH mylist "d" "e"         # Push to right
 
# Pop from list
LPOP mylist                  # Pop from left
RPOP mylist                  # Pop from right
 
# Get range
LRANGE mylist 0 -1          # Get all elements
 
# Get length
LLEN mylist
 
# Get by index
LINDEX mylist 0

Hash Operations

# Set hash field
HSET myhash field1 "value1" field2 "value2"
 
# Get hash field
HGET myhash field1
 
# Get all fields
HGETALL myhash
 
# Get all keys
HKEYS myhash
 
# Get all values
HVALS myhash
 
# Delete field
HDEL myhash field1
 
# Check field exists
HEXISTS myhash field1
 
# Get hash size
HLEN myhash

Set Operations

# Add to set
SADD myset "a" "b" "c"
 
# Get all members
SMEMBERS myset
 
# Check member exists
SISMEMBER myset "a"
 
# Get set size
SCARD myset
 
# Remove member
SREM myset "a"
 
# Get intersection
SINTER set1 set2
 
# Get union
SUNION set1 set2
 
# Get difference
SDIFF set1 set2

Sorted Set Operations

# Add to sorted set (score, member)
ZADD myzset 1 "one" 2 "two" 3 "three"
 
# Get range
ZRANGE myzset 0 -1
 
# Get range with scores
ZRANGE myzset 0 -1 WITHSCORES
 
# Get by score range
ZRANGEBYSCORE myzset 1 2
 
# Get reverse range
ZREVRANGE myzset 0 -1
 
# Get member score
ZSCORE myzset "one"
 
# Get sorted set size
ZCARD myzset
 
# Remove member
ZREM myzset "one"

Key Operations

# List all keys
KEYS *
 
# Search keys
KEYS user:*
 
# Count keys
DBSIZE
 
# Flush database
FLUSHDB
 
# Flush all databases
FLUSHALL
 
# Get key type
TYPE key
 
# Rename key
RENAME old_key new_key
 
# Random key
RANDOMKEY

Database Management

Select Database

# Select database (0-15)
SELECT 0
 
# View current database
DBSIZE

Backup & Restore

# Manual backup (RDB dump)
BGSAVE              # Background save
SAVE                # Foreground save (blocks)
LASTSAVE            # Check last save time
 
# Dump file location
/var/lib/redis/dump.rdb
 
# Backup dump file
sudo cp /var/lib/redis/dump.rdb /backup/dump.rdb
 
# Restore from backup
# Stop Redis
sudo systemctl stop redis-server
 
# Copy backup to Redis directory
sudo cp /backup/dump.rdb /var/lib/redis/dump.rdb
 
# Restart Redis
sudo systemctl start redis-server

Persistence Settings

# Check persistence settings
redis-cli CONFIG GET save
redis-cli CONFIG GET appendonly
 
# Enable AOF persistence
redis-cli CONFIG SET appendonly yes
 
# Get AOF file size
ls -lh /var/lib/redis/appendonly.aof

Firewall Configuration

# UFW (Ubuntu)
sudo ufw allow 6379
 
# Firewalld (CentOS)
sudo firewall-cmd --permanent --add-port=6379/tcp
sudo firewall-cmd --reload
 
# Allow specific IP only
sudo ufw allow from 192.168.1.100 to any port 6379

Security

Set Password

# Set password in configuration
sudo nano /etc/redis/redis.conf
# Add: requirepass your_strong_password
 
# Or set dynamically
redis-cli CONFIG SET requirepass "your_password"
 
# Connect with password
redis-cli -a your_password
 
# Or authenticate after connecting
redis-cli
> AUTH your_password

Disable Dangerous Commands

# In redis.conf, disable commands
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command KEYS ""
rename-command CONFIG ""
 
# Or rename them
rename-command FLUSHDB "FLUSHDB_disable_82347832"

Remote Access Security

# Only allow specific IPs
bind 127.0.0.1 192.168.1.100

# Or bind to all (with firewall)
bind 0.0.0.0

# Always use password
requirepass strong_password

Monitoring

Redis CLI Monitor

# Monitor commands in real-time
redis-cli MONITOR
 
# View current connections
redis-cli CLIENT LIST
 
# View memory usage
redis-cli INFO memory
 
# View statistics
redis-cli INFO stats
 
# View all info
redis-cli INFO

Performance Metrics

# Check latency
redis-cli --latency
 
# Check latency history
redis-cli --latency-history -i 1
 
# Slowlog (slow queries)
redis-cli SLOWLOG GET 10
redis-cli SLOWLOG LEN
redis-cli SLOWLOG RESET

Clustering (Optional)

Master-Slave Replication

# On slave server, in redis.conf
slaveof master-ip 6379

# Or set dynamically
redis-cli SLAVEOF master-ip 6379

# Check replication status
redis-cli INFO replication

Docker Management

# View running container
docker ps | grep redis
 
# View logs
docker logs -f redis
 
# Connect to container
docker exec -it redis redis-cli
 
# Stop container
docker stop redis
 
# Start container
docker start redis
 
# Remove container
docker rm redis
 
# Check container stats
docker stats redis

Troubleshooting

# Check if Redis is running
ps aux | grep redis-server
 
# Check port is listening
netstat -tlnp | grep 6379
 
# Test connection
redis-cli ping
 
# Check logs
sudo tail -f /var/log/redis/redis-server.log
 
# Check configuration
redis-cli CONFIG GET "*"
 
# Check memory usage
redis-cli INFO memory
 
# Check connections
redis-cli INFO clients
 
# Verify persistence
ls -la /var/lib/redis/
 
# Check RDB file
file /var/lib/redis/dump.rdb

Performance Tuning

# Increase max connections
redis-cli CONFIG SET maxclients 10000
 
# Set memory limit
redis-cli CONFIG SET maxmemory 1gb
 
# Set eviction policy
redis-cli CONFIG SET maxmemory-policy allkeys-lru
 
# Adjust slowlog
redis-cli CONFIG SET slowlog-log-slower-than 10000
redis-cli CONFIG SET slowlog-max-len 128
 
# AOF rewrite
redis-cli BGREWRITEAOF

Uninstall

Ubuntu/Debian

# Stop Redis
sudo systemctl stop redis-server
 
# Remove Redis
sudo apt remove redis-server -y
sudo apt autoremove -y
 
# Remove data
sudo rm -rf /var/lib/redis
sudo rm -rf /var/log/redis
sudo rm -rf /etc/redis

CentOS/RHEL

# Stop Redis
sudo systemctl stop redis
 
# Remove Redis
sudo yum remove redis -y
 
# Remove data
sudo rm -rf /var/lib/redis
sudo rm -rf /var/log/redis

Docker

# Stop and remove container
docker stop redis
docker rm redis
 
# Remove volume
docker volume rm redis-data