Skip to content

Instantly share code, notes, and snippets.

@drhema
Created April 24, 2025 11:27
Show Gist options
  • Save drhema/c77e7ad047dabc93cad84859503a1483 to your computer and use it in GitHub Desktop.
Save drhema/c77e7ad047dabc93cad84859503a1483 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# ===================================
# Enhanced Redis Installation Script for Phoenix Ecommerce App
# Optimized for caching workloads with security and performance settings
# ===================================
# Ensure the script is run as root or with sudo
if [ "$(id -u)" != "0" ]; then
echo "Please run this script as root (sudo)."
exit 1
fi
# Get Redis password
read -sp "Enter the desired Redis password (strong password recommended): " REDIS_PASS
echo
# Get server memory for automatic RAM allocation
TOTAL_MEM_KB=$(grep MemTotal /proc/meminfo | awk '{print $2}')
TOTAL_MEM_MB=$((TOTAL_MEM_KB / 1024))
# Use 30% of server memory for Redis, with a minimum of 128MB and maximum of 2GB
REDIS_MEMORY=$((TOTAL_MEM_MB * 30 / 100))
if [ $REDIS_MEMORY -lt 128 ]; then
REDIS_MEMORY=128
elif [ $REDIS_MEMORY -gt 2048 ]; then
REDIS_MEMORY=2048
fi
echo "====================================="
echo "Redis Installation & Configuration"
echo "====================================="
echo "Total system memory: ${TOTAL_MEM_MB}MB"
echo "Allocating ${REDIS_MEMORY}MB for Redis"
echo "====================================="
# 1. Stop and purge any existing Redis installation
echo "Removing previous Redis installation (if any)..."
systemctl stop redis-server || true
apt purge redis-server redis-tools -y
apt autoremove -y
# 2. Install Redis
echo "Installing Redis..."
apt update
apt install redis-server -y
# Check if it starts with default config
systemctl restart redis-server
if ! systemctl is-active --quiet redis-server; then
echo "ERROR: Redis failed to start with default configuration."
echo "Check 'systemctl status redis-server' and 'journalctl -xeu redis-server.service' for details."
exit 1
fi
echo "Redis started successfully with default configuration."
# 3. Configure Redis for ecommerce caching workload
REDIS_CONF="/etc/redis/redis.conf"
echo "Configuring Redis for ecommerce caching workload..."
# Backup the original configuration
cp $REDIS_CONF ${REDIS_CONF}.backup
# --- SECURITY SETTINGS ---
echo "Configuring security settings..."
# Set password
sed -i 's/^# requirepass .*/requirepass '"$REDIS_PASS"'/' $REDIS_CONF
grep -q "^requirepass" $REDIS_CONF || echo "requirepass $REDIS_PASS" >> $REDIS_CONF
# Network settings
sed -i 's/^bind .*/bind 0.0.0.0/' $REDIS_CONF
sed -i 's/^protected-mode .*/protected-mode no/' $REDIS_CONF
# --- MEMORY MANAGEMENT ---
echo "Configuring memory management..."
# Add memory limit and policy
echo "# Memory management settings - optimized for cache workload" >> $REDIS_CONF
echo "maxmemory ${REDIS_MEMORY}mb" >> $REDIS_CONF
echo "maxmemory-policy allkeys-lru" >> $REDIS_CONF
echo "" >> $REDIS_CONF
# --- PERSISTENCE SETTINGS ---
echo "Optimizing persistence settings for caching..."
# Adjust persistence for better cache performance
# Comment out all existing save directives
sed -i 's/^save /# save /' $REDIS_CONF
# Add our optimized persistence settings
echo "# Cache-optimized persistence (less frequent saves)" >> $REDIS_CONF
echo "save 900 1" >> $REDIS_CONF # Save if at least 1 key changed in 15 minutes
echo "save 300 100" >> $REDIS_CONF # Save if at least 100 keys changed in 5 minutes
echo "" >> $REDIS_CONF
# --- PERFORMANCE TUNING ---
echo "Applying performance optimizations..."
# Performance settings
echo "# Performance optimizations for ecommerce caching" >> $REDIS_CONF
echo "tcp-keepalive 300" >> $REDIS_CONF # Keep connections alive
echo "timeout 0" >> $REDIS_CONF # Don't timeout clients
echo "databases 2" >> $REDIS_CONF # We only need 2 DBs (0 for main, 1 for backup)
echo "loglevel notice" >> $REDIS_CONF # Reduced logging for performance
echo "# Disable expensive commands in production" >> $REDIS_CONF
echo "rename-command FLUSHALL \"\"" >> $REDIS_CONF # Disable dangerous commands
echo "rename-command FLUSHDB \"\"" >> $REDIS_CONF
echo "rename-command DEBUG \"\"" >> $REDIS_CONF
echo "" >> $REDIS_CONF
# --- LATENCY SETTINGS ---
echo "Optimizing for low latency..."
echo "# Latency optimizations" >> $REDIS_CONF
echo "no-appendfsync-on-rewrite yes" >> $REDIS_CONF # Don't sync during rewrites
echo "activerehashing yes" >> $REDIS_CONF # Enable rehashing for faster reads
echo "" >> $REDIS_CONF
# --- TLS/SSL REMINDER ---
echo "# TLS/SSL is recommended for production but requires manual setup" >> $REDIS_CONF
echo "# See https://redis.io/topics/encryption" >> $REDIS_CONF
echo "" >> $REDIS_CONF
# --- CLIENT OUTPUT/INPUT BUFFER LIMITS ---
echo "# Client buffer limits to prevent slow clients from affecting server" >> $REDIS_CONF
echo "client-output-buffer-limit normal 0 0 0" >> $REDIS_CONF
echo "client-output-buffer-limit replica 256mb 64mb 60" >> $REDIS_CONF
echo "" >> $REDIS_CONF
# 4. Restart Redis to apply changes
systemctl restart redis-server
# 5. Check if Redis starts with the new configuration
if systemctl is-active --quiet redis-server; then
# Get server's IP address for connection string
SERVER_IP=$(hostname -I | awk '{print $1}')
echo ""
echo "=========================================================="
echo "βœ… Redis installation and configuration completed successfully!"
echo "=========================================================="
echo ""
echo "πŸ“Š Redis Configuration Summary:"
echo "β€’ Memory allocated: ${REDIS_MEMORY}MB"
echo "β€’ Eviction policy: allkeys-lru (removes least recently used keys when memory is full)"
echo "β€’ Persistence: Optimized for caching (less frequent saves)"
echo "β€’ Network: Listening on all interfaces (0.0.0.0:6379)"
echo "β€’ Security: Password authentication enabled"
echo ""
echo "πŸ”— Redis Connection Information:"
echo "β€’ Host: ${SERVER_IP}"
echo "β€’ Port: 6379"
echo "β€’ Redis CLI: redis-cli -h ${SERVER_IP} -p 6379 -a ${REDIS_PASS}"
echo ""
echo "πŸ” For your Phoenix application, add this to your .env file:"
echo "REDIS_URL=redis://:${REDIS_PASS}@${SERVER_IP}:6379"
echo ""
echo "⚠️ IMPORTANT SECURITY NOTES:"
echo "1. Consider using a firewall (ufw/iptables) to restrict Redis port access"
echo "2. For production, consider enabling TLS/SSL encryption"
echo "3. The original Redis config is backed up at ${REDIS_CONF}.backup"
echo ""
echo "To test your Redis connection:"
echo "redis-cli -h ${SERVER_IP} -p 6379 -a ${REDIS_PASS} ping"
echo "Expected response: PONG"
echo "=========================================================="
else
echo "Redis failed to start after configuration changes."
echo "Reverting to original configuration..."
cp ${REDIS_CONF}.backup $REDIS_CONF
systemctl restart redis-server
echo "Check these logs for details:"
echo "- systemctl status redis-server"
echo "- journalctl -xeu redis-server.service"
exit 1
fi
# 6. Create a simple monitor script for Redis
MONITOR_SCRIPT="/usr/local/bin/redis-monitor.sh"
echo "#!/bin/bash" > $MONITOR_SCRIPT
echo "# Simple Redis monitoring script" >> $MONITOR_SCRIPT
echo "echo \"Redis Memory Usage:\"" >> $MONITOR_SCRIPT
echo "redis-cli -a ${REDIS_PASS} info memory | grep used_memory_human" >> $MONITOR_SCRIPT
echo "echo \"Redis Connected Clients:\"" >> $MONITOR_SCRIPT
echo "redis-cli -a ${REDIS_PASS} info clients | grep connected_clients" >> $MONITOR_SCRIPT
echo "echo \"Redis Cache Keys:\"" >> $MONITOR_SCRIPT
echo "redis-cli -a ${REDIS_PASS} --scan --pattern \"api:*\" | wc -l" >> $MONITOR_SCRIPT
chmod +x $MONITOR_SCRIPT
echo "βœ… Added Redis monitoring script: $MONITOR_SCRIPT"
echo "Run it anytime to check Redis memory usage and client connections."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment