
Redis Installation on Ubuntu 24.04 VPS
Redis delivers sub-millisecond response times. It can cut database load by up to 90%.
This guide walks you through complete Linux VPS Redis cache configuration, from installation through production optimization.
Update your system packages and install Redis from Ubuntu's official repository:
sudo apt update
sudo apt install redis-server redis-tools -y
Check your installation by verifying the Redis version:
redis-server --version
redis-cli --version
The default installation creates an auto-starting Redis service. Confirm it's running:
sudo systemctl status redis-server
Redis Configuration File Setup
Redis stores its main configuration in /etc/redis/redis.conf. Back up the original before making changes:
sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.backup
Open the configuration file with your editor:
sudo nano /etc/redis/redis.conf
Modify these critical settings for production:
# Bind to specific interface (replace with your VPS internal IP)
bind 127.0.0.1 10.0.0.100
# Set a strong password
requirepass your_strong_redis_password_here
# Disable dangerous commands
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command DEBUG ""
# Enable AOF persistence
appendonly yes
appendfsync everysec
The bind directive limits Redis access to specified IP addresses. Never bind to 0.0.0.0 in production.
Memory Management and Performance Tuning
Configure memory settings based on your VPS specs. For a 4GB VPS, allocate 1-2GB to Redis:
# Set maximum memory usage
maxmemory 2gb
# Configure eviction policy
maxmemory-policy allkeys-lru
# Optimize for your use case
timeout 300
tcp-keepalive 60
The allkeys-lru policy removes least recently used keys when memory limits are hit. Other options include:
volatile-lru: Remove LRU keys with expire setallkeys-random: Remove random keysvolatile-ttl: Remove keys with shortest TTL first
For high-traffic applications, add these system optimizations:
# Disable transparent huge pages
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
# Increase TCP backlog
echo 'net.core.somaxconn = 65535' | sudo tee -a /etc/sysctl.conf
# Apply changes
sudo sysctl -p
Security Hardening Configuration
Redis runs without authentication by default. Lock it down immediately.
Create a dedicated Redis user with minimal privileges:
sudo useradd --system --home /var/lib/redis --shell /bin/false redis
Set proper file permissions for Redis directories:
sudo chown -R redis:redis /var/lib/redis
sudo chmod 750 /var/lib/redis
sudo chmod 640 /etc/redis/redis.conf
Add security-focused settings to your config:
# Disable protected mode only after setting password
protected-mode yes
# Change default port
port 6380
# Enable SSL/TLS (optional but recommended)
tls-port 6381
tls-cert-file /etc/redis/tls/redis.crt
tls-key-file /etc/redis/tls/redis.key
Restart Redis to apply all changes:
sudo systemctl restart redis-server
sudo systemctl enable redis-server
Test your connection with the new password:
redis-cli -p 6380 -a your_strong_redis_password_here ping
Web Application Integration
Redis integrates with popular web frameworks. Here's how to connect from PHP, Node.js, and Python applications.
For PHP apps, install the Redis extension:
sudo apt install php-redis
sudo systemctl restart apache2 # or nginx/php-fpm
Configure PHP to use Redis as a session handler in /etc/php/8.3/apache2/php.ini:
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6380?auth=your_password"
For Node.js applications, install the redis client:
npm install redis
Set up a basic connection config:
const redis = require('redis');
const client = redis.createClient({
host: '127.0.0.1',
port: 6380,
password: 'your_password'
});
client.on('connect', () => {
console.log('Redis connected');
});
Consider using a HostMyCode VPS with SSD storage for optimal Redis performance. Fast disk I/O significantly improves persistence operations.
Monitoring and Performance Analysis
Redis includes built-in monitoring tools to track performance. Use redis-cli for real-time stats:
# Monitor all commands in real-time
redis-cli -p 6380 -a your_password monitor
# Get comprehensive server info
redis-cli -p 6380 -a your_password info
# Check memory usage
redis-cli -p 6380 -a your_password info memory
Key metrics to watch:
- used_memory: Current memory consumption
- connected_clients: Active client connections
- total_commands_processed: Commands executed since startup
- keyspace_hits vs keyspace_misses: Cache hit ratio
Create automated monitoring with this bash script:
#!/bin/bash
REDIS_CLI="redis-cli -p 6380 -a your_password"
MEMORY_USAGE=$($REDIS_CLI info memory | grep used_memory_human | cut -d: -f2 | tr -d '\r')
HIT_RATE=$($REDIS_CLI info stats | grep keyspace_hit_rate | cut -d: -f2 | tr -d '\r')
echo "$(date): Memory: $MEMORY_USAGE, Hit Rate: $HIT_RATE%" >> /var/log/redis-monitor.log
Run this via cron every 5 minutes to maintain performance logs.
Backup and Data Persistence
Redis offers two persistence methods: RDB snapshots and AOF (Append Only File). Configure both for maximum data protection:
# RDB settings
save 900 1
save 300 10
save 60 10000
# AOF settings
appendonly yes
appendfsync everysec
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
Create automated backup scripts for your Redis data:
#!/bin/bash
BACKUP_DIR="/backup/redis"
DATE=$(date +%Y%m%d_%H%M%S)
# Create backup directory
mkdir -p $BACKUP_DIR
# Trigger RDB snapshot
redis-cli -p 6380 -a your_password BGSAVE
# Wait for snapshot completion
while [ $(redis-cli -p 6380 -a your_password LASTSAVE) -eq $LAST_SAVE ]; do
sleep 1
done
# Copy files
cp /var/lib/redis/dump.rdb $BACKUP_DIR/dump_$DATE.rdb
cp /var/lib/redis/appendonly.aof $BACKUP_DIR/appendonly_$DATE.aof
Troubleshooting Common Issues
Redis configuration problems usually show up as connection failures or performance issues.
Here are diagnostic steps for common scenarios.
If Redis fails to start, check system logs:
sudo journalctl -u redis-server -f
Common startup errors:
- Permission denied: Check file ownership and permissions on
/var/lib/redis - Address already in use: Another process is using the configured port
- Invalid configuration: Syntax errors in
redis.conf
Test Redis connectivity from remote applications:
# Test basic connectivity
telnet your-vps-ip 6380
# Test authentication
redis-cli -h your-vps-ip -p 6380 -a your_password ping
Monitor slow queries that might hurt performance:
# Configure slow log
redis-cli -p 6380 -a your_password config set slowlog-log-slower-than 10000
# View slow queries
redis-cli -p 6380 -a your_password slowlog get 10
For detailed Redis tutorials and advanced configs, check our Redis cluster setup guide for high-availability deployments.
Ready to deploy Redis on a high-performance VPS? HostMyCode offers optimized Linux VPS hosting with SSD storage and full root access, perfect for Redis cache implementations. Our managed VPS hosting includes Redis optimization and 24/7 technical support.
Frequently Asked Questions
How much memory should I allocate to Redis on my VPS?
Allocate 25-50% of your total VPS memory to Redis, depending on your application needs. For a 4GB VPS, 1-2GB works well. Monitor actual usage and adjust as needed.
Should I use RDB or AOF persistence?
Use both for maximum data protection. RDB provides faster restarts and smaller files. AOF offers better durability. Configure RDB for regular snapshots and AOF for continuous logging.
How do I secure Redis against unauthorized access?
Always set a strong password and bind to specific interfaces (never 0.0.0.0). Disable dangerous commands and run Redis as a non-privileged user. Consider TLS encryption for network communication.
What's the difference between Redis and Memcached?
Redis supports complex data structures (lists, sets, hashes), persistence, and atomic operations. Memcached is simpler and uses less memory per key but only supports string values. Choose Redis for complex caching needs.
How can I monitor Redis performance in production?
Use the built-in INFO command and monitor slow queries with SLOWLOG. Track memory usage and hit rates. Consider external monitoring tools like Redis Insight or Grafana dashboards for comprehensive metrics.