1.拉取redis5.0.5镜像
docker pull redis:5.0.5
2.创建conf配置文件模板
创建目录
mkdir -p /usr/local/redis/redis-cluster
在目录中创建文件redis-cluster.tmpl,内容如下:
port ${PORT}
protected-mode no
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 192.168.31.159
cluster-announce-port ${PORT}
cluster-announce-bus-port 1${PORT}
appendonly yes
masterauth 123456
requirepass 123456
以上代码中的192.168.31.159 主机ip地址
123456 为密码
3.批量创建conf配置文件
for port in `seq 7000 7005`; do \
mkdir -p ./${port}/conf \
&& PORT=${port} envsubst < ./redis-cluster.tmpl > ./${port}/conf/redis.conf \
&& mkdir -p ./${port}/data; \
done
4.创建网络
docker network create redis-net
5.创建容器
for port in `seq 7000 7005`; do \
docker run -d -ti -p ${port}:${port} -p 1${port}:1${port} \
-v /usr/local/redis/redis-cluster/${port}/conf/redis.conf:/usr/local/etc/redis/redis.conf \
-v /usr/local/redis/redis-cluster/${port}/data:/data \
--restart always --name redis-${port} --net redis-net\
--sysctl net.core.somaxconn=1024 redis:5.0.5 redis-server /usr/local/etc/redis/redis.conf; \
done
6.查看容器IP地址,搭建集群备用
for port in `seq 7000 7005`; do \
echo -n "$(docker inspect --format '{{ (index .NetworkSettings.Networks "redis-net").IPAddress }}' "redis-${port}")":${port}' ' ; \
done
复制控制台输出结果,如下
172.18.0.2:7000 172.18.0.3:7001 172.18.0.4:7002 172.18.0.5:7003 172.18.0.6:7004 172.18.0.7:7005
7.开放防火墙端口
for port in `seq 7000 7005`; do firewall-cmd --zone=public --add-port=${port}/tcp --permanent; done
for port in `seq 17001 17005`; do firewall-cmd --zone=public --add-port=${port}/tcp --permanent; done
firewall-cmd --reload
8.进入容器中,执行搭建集群命令
[root@rabbitmq ~]# docker exec -it redis-7000 bash
root@874b9667b48c:/data# redis-cli -a 123456 --cluster create 172.18.0.2:7000 172.18.0.3:7001 172.18.0.4:7002 172.18.0.5:7003 172.18.0.6:7004 172.18.0.7:7005 --cluster-replicas 1
9.总结
cluster-announce-ip 的IP地址要正确。
防火墙开放端口也很关键。缺少这一步,创建集群的时候会一直等待。