Docker 安装 Redis 哨兵模式
Docker 安装 Redis 哨兵模式(三节点 + Host 网络)
以下是使用 Docker 在三台机器上部署 Redis 哨兵模式(Sentinel)的完整方案,采用 host
网络模式以提高性能。
架构说明
- 3台物理机:分别部署 1个 Redis 主节点 + 1个从节点 + 3个 Sentinel
- 网络模式:
--net=host
(直接使用宿主机网络,避免 NAT 性能损耗) - 端口规划:
- Redis: 6379
- Sentinel: 26379
1. 机器准备
主机 | IP | 角色 |
---|---|---|
node1 | 192.168.1.10 | Redis Master + Sentinel1 |
node2 | 192.168.1.11 | Redis Slave + Sentinel2 |
node3 | 192.168.1.12 | Redis Slave + Sentinel3 |
2. 每台机器操作步骤
(1) 创建数据目录
mkdir -p /data/redis/{data,conf} /data/sentinel
(2) 配置 Redis(所有节点)
编辑 /data/redis/conf/redis.conf
:
bind 0.0.0.0
port 6379
daemonize no
pidfile /var/run/redis.pid
dir /data
appendonly yes
cluster-enabled no
(3) 配置 Sentinel(所有节点)
编辑 /data/sentinel/sentinel.conf
:
port 26379
sentinel monitor mymaster 192.168.1.10 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 10000
sentinel parallel-syncs mymaster 1
3. 启动容器
在 node1 (Master) 上执行:
# 启动 Redis 主节点
docker run -d --name redis \--net=host \-v /data/redis/data:/data \-v /data/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf \redis:7.0 redis-server /usr/local/etc/redis/redis.conf# 启动 Sentinel
docker run -d --name sentinel \--net=host \-v /data/sentinel/sentinel.conf:/usr/local/etc/redis/sentinel.conf \redis:7.0 redis-sentinel /usr/local/etc/redis/sentinel.conf
在 node2/node3 (Slave) 上执行:
# 启动 Redis 从节点(注意替换 MASTER_IP)
docker run -d --name redis \--net=host \-v /data/redis/data:/data \-v /data/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf \redis:7.0 redis-server /usr/local/etc/redis/redis.conf \--replicaof 192.168.1.10 6379# 启动 Sentinel(配置同 node1)
docker run -d --name sentinel \--net=host \-v /data/sentinel/sentinel.conf:/usr/local/etc/redis/sentinel.conf \redis:7.0 redis-sentinel /usr/local/etc/redis/sentinel.conf
4. 验证集群
(1) 检查主从复制
# 在主节点执行
docker exec redis redis-cli info replication
输出应显示:
role:master
connected_slaves:2
slave0:ip=192.168.1.11,port=6379,state=online
slave1:ip=192.168.1.12,port=6379,state=online
(2) 测试 Sentinel 故障转移
# 手动关闭主节点 Redis
docker stop redis# 在任意 Sentinel 节点查看选举结果
docker exec sentinel redis-cli -p 26379 sentinel get-master-addr-by-name mymaster
约 10 秒后应返回新的主节点 IP。
5. 关键配置说明
参数 | 说明 |
---|---|
sentinel monitor mymaster... | 监控名为 mymaster 的主节点,2表示需要2个Sentinel同意才触发故障转移 |
down-after-milliseconds 5000 | 5秒无响应判定为宕机 |
failover-timeout 10000 | 故障转移超时时间(毫秒) |
--net=host | 使用主机网络,避免端口映射带来的性能损失 |
常见问题解决
-
主从无法连接:
- 检查防火墙是否开放 6379/26379 端口
- 确保所有节点的
redis.conf
中bind 0.0.0.0
-
Sentinel 不触发故障转移:
- 确认至少有两个 Sentinel 能连通主节点
- 检查
sentinel.conf
中的主节点 IP 是否正确
-
Host 网络模式警告:
- 如果使用云服务器,需确保安全组允许节点间通信
扩展建议
- 持久化:建议同时启用 RDB 和 AOF
- 监控:使用
redis-cli info
或 Prometheus + Grafana 监控集群状态 - 安全:通过
requirepass
和masterauth
配置密码认证
此方案适合生产环境,如需更高可用性,可增加 Redis 和 Sentinel 节点数量。