Redis
Redis is a high-performance in-memory key-value database widely used for caching, session management, message queues, and more. This article covers Redis installation, core configuration, service management, command-line tool usage, persistence strategies, and security hardening.
Versions Across Distributions
Section titled “Versions Across Distributions”Install Redis
Section titled “Install Redis”Install from System Repository (EL 9)
Section titled “Install from System Repository (EL 9)”The EL 9 AppStream repository includes Redis:
sudo dnf install redis -yUsing the Remi Repository (for Latest Version)
Section titled “Using the Remi Repository (for Latest Version)”To install the latest stable version of Redis:
sudo dnf install epel-release -ysudo dnf install https://rpms.remirepo.net/enterprise/remi-release-$(rpm -E %{rhel}).rpm -ysudo dnf module reset redis -ysudo dnf module enable redis:remi-7.2 -ysudo dnf install redis -yStart the Service
Section titled “Start the Service”sudo systemctl start redissudo systemctl enable redissudo systemctl status redisVerify that Redis is running properly:
redis-cli pingIf it returns PONG, Redis is running correctly.
Core Configuration
Section titled “Core Configuration”The main Redis configuration file is located at /etc/redis/redis.conf (on some systems, /etc/redis.conf).
redis-cli CONFIG GET dirfind /etc -name "redis.conf" 2>/dev/nullBack up the configuration before making changes:
sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.bakBind Address
Section titled “Bind Address”By default, Redis only listens on 127.0.0.1, which is the most secure setting.
grep "^bind" /etc/redis/redis.confIf you need Redis to accept connections from a specific network:
sudo sed -i 's/^bind 127.0.0.1.*/bind 127.0.0.1 192.168.1.10/' /etc/redis/redis.confNote: Never bind Redis directly to
0.0.0.0and expose it to the public internet. Redis is not designed to be directly internet-facing.
Set a Password (requirepass)
Section titled “Set a Password (requirepass)”A password must be set in production environments:
sudo sed -i 's/^# requirepass foobared/requirepass YourStrongRedisPassword!/' /etc/redis/redis.confOr add it directly to the configuration file:
echo 'requirepass YourStrongRedisPassword!' | sudo tee -a /etc/redis/redis.confConnecting with a password:
redis-cli -a YourStrongRedisPassword!
# Or connect first then authenticateredis-cli# Once connected, run: AUTH YourStrongRedisPassword!Change the Port
Section titled “Change the Port”sudo sed -i 's/^port 6379/port 6380/' /etc/redis/redis.confSet Maximum Memory
Section titled “Set Maximum Memory”Limit the maximum memory Redis can use and the eviction policy when memory is full:
sudo tee -a /etc/redis/redis.conf << 'EOF'
# Maximum memory limitmaxmemory 256mb
# Memory eviction policy# allkeys-lru: Evict the least recently used key from all keys# volatile-lru: Evict only from keys with an expiration set# noeviction: Do not evict; return errors on writes when memory is fullmaxmemory-policy allkeys-lruEOFApply Configuration Changes
Section titled “Apply Configuration Changes”sudo systemctl restart redissystemctl Service Management
Section titled “systemctl Service Management”# Start Redissudo systemctl start redis
# Stop Redissudo systemctl stop redis
# Restart Redissudo systemctl restart redis
# Check statussudo systemctl status redis
# Enable at bootsudo systemctl enable redis
# Disable at bootsudo systemctl disable redis
# View Redis logssudo journalctl -u redis -fView Redis Runtime Information
Section titled “View Redis Runtime Information”redis-cli INFO
# View specific sectionsredis-cli INFO serverredis-cli INFO memoryredis-cli INFO clientsredis-cli INFO statsredis-cli Basic Operations
Section titled “redis-cli Basic Operations”redis-cli is the Redis command-line client tool.
String Operations
Section titled “String Operations”redis-cli
# Set key-value pairsSET name "CentOS Fan"SET counter 100
# Get valuesGET nameGET counter
# Set with expiration (seconds)SET session:abc123 "user_data" EX 3600
# Check remaining TTLTTL session:abc123
# Increment/DecrementINCR counterDECR counterINCRBY counter 10Hash Operations
Section titled “Hash Operations”# Set hash fields
# Get a single fieldHGET user:1 name
# Get all fields and valuesHGETALL user:1
# Delete a fieldHDEL user:1 ageList Operations
Section titled “List Operations”# Push from the leftLPUSH queue "task1" "task2" "task3"
# Pop from the rightRPOP queue
# View list contentsLRANGE queue 0 -1
# List lengthLLEN queueSet Operations
Section titled “Set Operations”# Add membersSADD tags "linux" "centos" "redis"
# View all membersSMEMBERS tags
# Check if a member existsSISMEMBER tags "linux"
# Set sizeSCARD tagsKey Management
Section titled “Key Management”# View all keys (use with caution in production)KEYS *
# Use SCAN for safe iteration (recommended)SCAN 0 MATCH "user:*" COUNT 10
# Check if a key existsEXISTS name
# Delete a keyDEL name
# Set expiration timeEXPIRE counter 300
# Check data type of a keyTYPE counter
# View total number of keys in the databaseDBSIZE
# Flush current database (dangerous)# FLUSHDB
# Flush all databases (extremely dangerous)# FLUSHALLRDB and AOF Persistence
Section titled “RDB and AOF Persistence”Redis provides two persistence methods that can be used individually or together.
RDB Snapshots
Section titled “RDB Snapshots”RDB writes in-memory data snapshots to disk at specified intervals. The files are compact and fast to restore, but data after the last snapshot may be lost.
grep -n "^save\|^dbfilename\|^dir" /etc/redis/redis.confDefault RDB rules in the configuration file:
# At least 1 key modified within 900 secondssave 900 1# At least 10 keys modified within 300 secondssave 300 10# At least 10000 keys modified within 60 secondssave 60 10000
# RDB file namedbfilename dump.rdb
# RDB file storage directorydir /var/lib/redisManually trigger an RDB snapshot:
# Blocking method (not recommended for production)redis-cli SAVE
# Background async method (recommended)redis-cli BGSAVE
# Check last snapshot timeredis-cli LASTSAVEAOF Append-Only Log
Section titled “AOF Append-Only Log”AOF (Append Only File) records every write command, providing higher data safety but larger file sizes.
sudo sed -i 's/^appendonly no/appendonly yes/' /etc/redis/redis.confAOF sync policy configuration:
# always - Sync on every write command, safest but slowest# everysec - Sync once per second (recommended, balances performance and safety)# no - Let the OS decide when to syncappendfsync everysecAOF rewrite (compaction) configuration:
# Trigger rewrite when AOF file grows 100% beyond the size after last rewriteauto-aof-rewrite-percentage 100# Minimum 64MB AOF file size to trigger rewriteauto-aof-rewrite-min-size 64mbManually trigger AOF rewrite:
redis-cli BGREWRITEAOFEnable Both RDB and AOF (Recommended)
Section titled “Enable Both RDB and AOF (Recommended)”sudo tee -a /etc/redis/redis.conf << 'EOF'
# Enable AOFappendonly yesappendfsync everysec
# Keep default RDB configuration# Redis prioritizes AOF for data recovery on restart (as AOF data is more complete)EOFsudo systemctl restart redisBack Up Redis Data
Section titled “Back Up Redis Data”sudo tee /usr/local/bin/redis-backup.sh << 'SCRIPT'#!/bin/bashBACKUP_DIR="/backup/redis"DATE=$(date +%Y%m%d_%H%M%S)REDIS_DATA="/var/lib/redis"RETENTION_DAYS=7
mkdir -p "$BACKUP_DIR"
# Trigger RDB snapshotredis-cli BGSAVEsleep 5
# Copy the RDB filecp "${REDIS_DATA}/dump.rdb" "${BACKUP_DIR}/dump_${DATE}.rdb"
# If AOF is enabled, also back up the AOF fileif [ -f "${REDIS_DATA}/appendonly.aof" ]; then cp "${REDIS_DATA}/appendonly.aof" "${BACKUP_DIR}/appendonly_${DATE}.aof"fi
# Clean up old backupsfind "$BACKUP_DIR" -name "*.rdb" -mtime +${RETENTION_DAYS} -deletefind "$BACKUP_DIR" -name "*.aof" -mtime +${RETENTION_DAYS} -delete
echo "Redis backup completed: ${BACKUP_DIR}"SCRIPT
sudo chmod +x /usr/local/bin/redis-backup.shSecurity Hardening
Section titled “Security Hardening”Set a Strong Password
Section titled “Set a Strong Password”This was covered in the “Set a Password” section above. The importance is worth emphasizing again: Redis executes commands extremely fast, making weak passwords very easy to brute-force.
redis-cli CONFIG GET requirepassDisable Dangerous Commands
Section titled “Disable Dangerous Commands”Some commands pose significant risks in production and can be disabled by renaming them to an empty string:
sudo tee -a /etc/redis/redis.conf << 'EOF'
# Disable dangerous commandsrename-command FLUSHDB ""rename-command FLUSHALL ""rename-command DEBUG ""rename-command CONFIG "REDIS_CONFIG_b4f2e8a1"EOFNote: After disabling the
CONFIGcommand, you must use the renamed version to execute it. Use this configuration with caution in Sentinel and Cluster modes.
Limit Client Connections
Section titled “Limit Client Connections”sudo sed -i 's/^# maxclients 10000/maxclients 5000/' /etc/redis/redis.confProtected Mode Notes
Section titled “Protected Mode Notes”Redis has protected-mode enabled by default, which rejects external connections when no password is set and the bind address is not 127.0.0.1. Always keep this option enabled:
grep "^protected-mode" /etc/redis/redis.confConfigure the Firewall
Section titled “Configure the Firewall”If Redis needs to accept remote connections, access sources must be restricted through the firewall:
# Allow only a specific IPsudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" port port="6379" protocol="tcp" accept'sudo firewall-cmd --reloadDo not open the Redis port to all sources:
# Not recommended! Do not open the Redis port to everyone# sudo firewall-cmd --permanent --add-port=6379/tcpRun as a Non-Privileged User
Section titled “Run as a Non-Privileged User”By default, Redis already runs as the redis user. You can confirm this:
ps aux | grep redis-serverSecurity Checklist
Section titled “Security Checklist”Use the following commands to quickly check Redis security status:
echo "=== Bind Address ==="redis-cli CONFIG GET bind
echo "=== Password Setting ==="redis-cli CONFIG GET requirepass
echo "=== Protected Mode ==="redis-cli CONFIG GET protected-mode
echo "=== Listening Port ==="redis-cli CONFIG GET port
echo "=== Maximum Memory ==="redis-cli CONFIG GET maxmemory
echo "=== Connected Clients ==="redis-cli INFO clients | grep connected_clientsCommon Operations Quick Reference
Section titled “Common Operations Quick Reference”# Start / Stop / Restartsudo systemctl start redissudo systemctl stop redissudo systemctl restart redis
# Connect to Redisredis-cliredis-cli -a passwordredis-cli -h host -p port -a password
# View Redis versionredis-server --version
# Monitor all commands in real time (for debugging, use with caution in production)redis-cli MONITOR
# View slow query logredis-cli SLOWLOG GET 10
# View memory usageredis-cli INFO memory
# View memory usage of a specific keyredis-cli MEMORY USAGE keyname
# Modify configuration at runtime (no restart needed)redis-cli CONFIG SET maxmemory 512mbredis-cli CONFIG SET maxmemory-policy allkeys-lru
# Write runtime configuration to the configuration fileredis-cli CONFIG REWRITEFurther Reading
Section titled “Further Reading”- Nginx Reverse Proxy — Frontend proxy configuration
- Firewall — Access control