docker-compose 搭建 redis 集群
准备配置文件
bind 0.0.0.0
# redis端口
port ${PORT}
requirepass redispwd
# 关闭保护模式
protected-mode no
# 开启集群
cluster-enabled yes
# 集群节点配置
cluster-config-file nodes.conf
# 超时
cluster-node-timeout 5000
# 集群节点IP host模式为宿主机IP
cluster-announce-ip 这里放宿主机ip
# 集群节点端口 7001 - 7006
cluster-announce-port ${PORT}
cluster-announce-bus-port 1${PORT}
# 开启 appendonly 备份模式
appendonly yes
# 每秒钟备份
appendfsync everysec
# 对aof文件进行压缩时,是否执行同步操作
no-appendfsync-on-rewrite no
# 当目前aof文件大小超过上一次重写时的aof文件大小的100%时会再次进行重写
auto-aof-rewrite-percentage 100
# 重写前AOF文件的大小最小值 默认 64mb
auto-aof-rewrite-min-size 64mb
集群节点文件生成
for port in `seq 7001 7006`; do \
mkdir -p ./redis-cluster/${port}/conf \
&& PORT=${port} envsubst < ./redis.conf > ./redis-cluster/${port}/conf/redis.conf \
&& mkdir -p ./redis-cluster/${port}/data; \
done
准备 compose 文件
version: "3.1"
services:
redis1:
image: redis:5.0.3
container_name: redis1
restart: always
networks:
- test_net
ports:
- 7001:7001
- 17001:17001
volumes:
- ./redis-cluster/7001/conf/redis.conf:/etc/redis/redis.conf
- ./redis-cluster/7001/data:/data
command:
["redis-server", "/etc/redis/redis.conf"]
redis2:
image: redis:5.0.3
container_name: redis2
restart: always
networks:
- test_net
ports:
- 7002:7002
- 17002:17002
volumes:
- ./redis-cluster/7002/conf/redis.conf:/etc/redis/redis.conf
- ./redis-cluster/7002/data:/data
command:
["redis-server", "/etc/redis/redis.conf"]
redis3:
image: redis:5.0.3
container_name: redis3
restart: always
networks:
- test_net
ports:
- 7003:7003
- 17003:17003
volumes:
- ./redis-cluster/7003/conf/redis.conf:/etc/redis/redis.conf
- ./redis-cluster/7003/data:/data
command:
["redis-server", "/etc/redis/redis.conf"]
redis4:
image: redis:5.0.3
container_name: redis4
restart: always
networks:
- test_net
ports:
- 7004:7004
- 17004:17004
volumes:
- ./redis-cluster/7004/conf/redis.conf:/etc/redis/redis.conf
- ./redis-cluster/7004/data:/data
command:
["redis-server", "/etc/redis/redis.conf"]
redis5:
image: redis:5.0.3
container_name: redis5
restart: always
networks:
- test_net
ports:
- 7005:7005
- 17005:17005
volumes:
- ./redis-cluster/7005/conf/redis.conf:/etc/redis/redis.conf
- ./redis-cluster/7005/data:/data
command:
["redis-server", "/etc/redis/redis.conf"]
redis6:
image: redis:5.0.3
container_name: redis6
restart: always
networks:
- test_net
ports:
- 7006:7006
- 17006:17006
volumes:
- ./redis-cluster/7006/conf/redis.conf:/etc/redis/redis.conf
- ./redis-cluster/7006/data:/data
command:
["redis-server", "/etc/redis/redis.conf"]
networks:
test_net:
external: true
配置相对比较简单,需要注意下docker网络,提前创建好(docker network ls 可以查看具体有哪些网络)
redis 集群正式搭建
docker-compose -f '填写上述的compose文件名' up -d
进入启动的端口为7001的容器
docker exec -it container_id bash
集群搭建指令(提前关闭防火墙 iptables -F,也有别的指令,自行百度即可):
redis-cli -p 7001 -a redispwd --cluster create 宿主机ip:7001 宿主机ip:7002 宿主机ip:7003 宿主机ip:7004 宿主机ip:7005 宿主机ip:7006 --cluster-replicas 1
等待集群自行搭建完成即可。
需要说明一下:此处搭建的为伪集群,即同一宿主机,不同端口。