Skip to content

Deploying Redis 7 with Sentinel for automatic failover on Ubuntu 22.04

Stand up a hardened Redis 7 cluster with 1 primary + 2 replicas + 3 Sentinels on Ubuntu 22.04 — AOF persistence, ACL, TLS, automatic failover under quorum.

You install Redis on a single Ubuntu VM, point the application at it, and traffic is healthy. Six months later the primary VM gets a hypervisor maintenance window, the application starts erroring with LOADING Redis is loading the dataset in memory, your queue workers back off into exponential retries, and someone in the chat asks why the cache layer takes down the whole product. The answer is that you deployed Redis, not a Redis cluster — no replica, no Sentinel, no failover, no AOF — and you found out at the worst possible time that “in memory” means “gone” if a single node restarts.

What’s happening

Production-grade Redis isn’t a single process. It’s a primary holding the working set, two replicas streaming the RDB + replication backlog, and three Sentinels — odd number for quorum — watching the primary and ready to promote a replica when a majority of Sentinels agree the primary is down. Persistence has to be AOF (appendonly yes, appendfsync everysec) because RDB-only persistence loses the last few seconds on a crash, which is exactly what you don’t want for a queue backend. Bind has to be the private interface, never 0.0.0.0; protected-mode is the last line of defence after that. ACL replaces the legacy single-password model — a default user with no commands plus per-purpose users (app, replica, sentinel, admin). Typical failover under a healthy three-Sentinel quorum is 0.5-2 seconds; that only holds if the Sentinels can talk to each other.

How to verify

From any node, ask Sentinel who the primary is:

redis-cli -p 26379 sentinel masters
# 1)  1) "name"
#     2) "mymaster"
#     7) "ip"
#     8) "10.20.0.11"
#    15) "num-other-sentinels"
#    16) "2"

num-other-sentinels must be 2 (the other two Sentinels see you). If it’s 0, the Sentinels are deaf to each other and failover will never trigger.

Replication topology from the primary:

redis-cli -p 6379 -a "<password>" info replication
# role:master
# connected_slaves:2
# slave0:ip=10.20.0.12,port=6379,state=online,offset=...,lag=0
# slave1:ip=10.20.0.13,port=6379,state=online,offset=...,lag=0

lag should be 0 or 1 on every replica. A persistent lag above 5 means replication is bandwidth-bound or the replica is CPU-bound on AOF rewrite.

Trigger a controlled failover to validate the wiring:

redis-cli -p 26379 sentinel failover mymaster

Sentinel logs should show “+switch-master” within a couple of seconds.

The fix

Save the script as /root/setup-redis-sentinel-node.sh, edit the per-node variables, and run on each of the three Ubuntu 22.04 nodes. It performs the full installer: base hardening (UFW, fail2ban, unattended-upgrades, SSH key-only), kernel/sysctl tuning Redis specifically needs (vm.overcommit_memory=1, net.core.somaxconn=4096, transparent huge pages disabled at boot), Redis 7.x from the official APT repo, a hardened redis.conf with ACL + AOF + TLS, a hardened sentinel.conf with quorum 2, systemd unit overrides raising LimitNOFILE to 200000, a private-network-only bind, and a listener-wait loop. The first node bootstraps as primary; nodes two and three start as replicas.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Redis 7 + Sentinel installer
### Run on each of 3 nodes after editing the variables below
### No local backups; assumes VM-level snapshots
### A nightly RDB copy off-host is an additional layer

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
NODE_NAME="redis01"             # redis01 / redis02 / redis03
NODE_IP="10.20.0.11"            # this node's private IP
PEER_IPS=("10.20.0.11" "10.20.0.12" "10.20.0.13")
PRIMARY_IP="10.20.0.11"         # the bootstrap primary's IP
IS_PRIMARY="yes"                # "yes" only on the first node
APP_PASSWORD="CHANGE_ME_APP"
REPL_PASSWORD="CHANGE_ME_REPL"
SENTINEL_PASSWORD="CHANGE_ME_SEN"
ADMIN_PASSWORD="CHANGE_ME_ADM"
# =====================

echo
echo "========================================"
echo "Redis ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

export DEBIAN_FRONTEND=noninteractive

echo "==> Updating base OS"
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install curl wget gnupg lsb-release ca-certificates \
  chrony fail2ban unattended-upgrades lsof tcpdump dnsutils \
  iproute2 ufw

systemctl enable --now chrony

echo "==> UFW (private network only)"
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
for ip in "${PEER_IPS[@]}"; do
  ufw allow from "${ip}" to any port 6379 proto tcp
  ufw allow from "${ip}" to any port 26379 proto tcp
done
ufw --force enable

echo "==> Kernel/sysctl tuning for Redis"
cat > /etc/sysctl.d/99-redis.conf <<'SYSCTL'
vm.overcommit_memory = 1
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
fs.file-max = 2097152
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-redis.conf <<'LIMITS'
redis soft nofile 200000
redis hard nofile 200000
LIMITS

echo "==> Disabling transparent huge pages"
cat > /etc/systemd/system/disable-thp.service <<'THP'
[Unit]
Description=Disable Transparent Huge Pages
DefaultDependencies=no
After=sysinit.target local-fs.target
Before=redis-server.service

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled; echo never > /sys/kernel/mm/transparent_hugepage/defrag'

[Install]
WantedBy=basic.target
THP
systemctl daemon-reload
systemctl enable --now disable-thp

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart ssh

echo "==> fail2ban + unattended-upgrades"
cat > /etc/fail2ban/jail.d/sshd.local <<'F2B'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
F2B
systemctl enable --now fail2ban
dpkg-reconfigure -plow unattended-upgrades

echo "==> Adding Redis APT repo"
curl -fsSL https://packages.redis.io/gpg | gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" \
  > /etc/apt/sources.list.d/redis.list
apt-get update
apt-get -y install redis

systemctl stop redis-server || true

echo "==> Generating self-signed TLS for inter-node"
mkdir -p /etc/redis/tls
cd /etc/redis/tls
if [[ ! -f redis.crt ]]; then
  openssl req -x509 -newkey rsa:4096 -nodes -days 1825 \
    -subj "/CN=redis-${NODE_NAME}" \
    -addext "subjectAltName=IP:${NODE_IP},IP:127.0.0.1" \
    -keyout redis.key -out redis.crt
  chown redis:redis redis.key redis.crt
  chmod 600 redis.key
fi
cd /

echo "==> Writing redis.conf"
cat > /etc/redis/redis.conf <<EOF
bind ${NODE_IP} 127.0.0.1
protected-mode yes
port 6379
tcp-backlog 511
timeout 0
tcp-keepalive 300

daemonize no
supervised systemd
pidfile /run/redis/redis-server.pid
loglevel notice
logfile /var/log/redis/redis-server.log

databases 16
always-show-logo no

save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /var/lib/redis

appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes

maxmemory-policy allkeys-lru
maxclients 10000

replica-read-only yes
replica-serve-stale-data yes
repl-diskless-sync yes
repl-diskless-sync-delay 5
masterauth ${REPL_PASSWORD}
masteruser replica

requirepass ${ADMIN_PASSWORD}
user default off nopass nocommands
user app on >${APP_PASSWORD} ~* &* -@dangerous +@all
user replica on >${REPL_PASSWORD} +psync +replconf +ping
user sentinel on >${SENTINEL_PASSWORD} +auth +client|kill +client|list +client|no-evict +client|info +client|setname +client|getname +client|unpause +client|pause +ping +subscribe +publish +psubscribe +unsubscribe +punsubscribe +hello +reset +failover +info +replicaof +slaveof +debug +script|kill +exec +multi +sentinel +shutdown +role
user admin on >${ADMIN_PASSWORD} ~* &* +@all

EOF

if [[ "${IS_PRIMARY}" != "yes" ]]; then
  cat >> /etc/redis/redis.conf <<EOF

replicaof ${PRIMARY_IP} 6379
EOF
fi

chown redis:redis /etc/redis/redis.conf
chmod 640 /etc/redis/redis.conf

echo "==> systemd override for LimitNOFILE"
mkdir -p /etc/systemd/system/redis-server.service.d
cat > /etc/systemd/system/redis-server.service.d/override.conf <<'OV'
[Service]
LimitNOFILE=200000
OV

echo "==> Writing sentinel.conf"
cat > /etc/redis/sentinel.conf <<EOF
port 26379
bind ${NODE_IP} 127.0.0.1
protected-mode yes
daemonize no
supervised systemd
pidfile /run/redis/redis-sentinel.pid
logfile /var/log/redis/redis-sentinel.log
dir /var/lib/redis

sentinel monitor mymaster ${PRIMARY_IP} 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel auth-pass mymaster ${ADMIN_PASSWORD}
sentinel auth-user mymaster admin
sentinel resolve-hostnames no
sentinel announce-hostnames no
sentinel deny-scripts-reconfig yes
requirepass ${SENTINEL_PASSWORD}
EOF

chown redis:redis /etc/redis/sentinel.conf
chmod 640 /etc/redis/sentinel.conf

cat > /etc/systemd/system/redis-sentinel.service <<'SEN'
[Unit]
Description=Redis Sentinel
After=network.target

[Service]
Type=notify
User=redis
Group=redis
ExecStart=/usr/bin/redis-sentinel /etc/redis/sentinel.conf --supervised systemd
Restart=on-failure
LimitNOFILE=65535
PrivateTmp=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
SEN

systemctl daemon-reload
systemctl enable --now redis-server
systemctl enable --now redis-sentinel

echo "==> Waiting for listeners"
for i in {1..30}; do
  if ss -lntp | grep -q ":6379\b" && ss -lntp | grep -q ":26379\b"; then break; fi
  sleep 1
done

if ! ss -lntp | grep -q ":6379\b"; then
  echo "Redis failed to listen on 6379"
  journalctl -u redis-server -n 100 --no-pager
  exit 1
fi

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(6379|26379)\b' || true
echo
echo "Replication:"
redis-cli -h ${NODE_IP} -p 6379 -a "${ADMIN_PASSWORD}" --no-auth-warning info replication || true
echo
echo "Sentinel masters:"
redis-cli -h ${NODE_IP} -p 26379 -a "${SENTINEL_PASSWORD}" --no-auth-warning sentinel masters || true
echo
echo "Connect from app:"
echo "redis-cli -h ${PRIMARY_IP} -p 6379 --user app --pass <APP_PASSWORD>"
echo
echo "Repeat on the other nodes with IS_PRIMARY=no."

Make it executable and run on each node — the primary first, then the two replicas:

chmod 700 /root/setup-redis-sentinel-node.sh
/root/setup-redis-sentinel-node.sh

After all three are up, do a failover drill: redis-cli -p 26379 -a "<sentinel_pw>" sentinel failover mymaster. The promotion should land within a couple of seconds and the old primary should rejoin as a replica automatically. Add a nightly BGREWRITEAOF + copy of the AOF off-host as a defensive layer; AOF persistence on disk doesn’t help if the whole region loses power.

For Redis HA you don’t have to operate yourself, we run it inside Cloud PaaS under Managed Cloud Ops — start a conversation.