拉取redis镜像
docker pull redis:5.0.3
增加配置文件redis-cluster.tmpl
在用户目录下创建文件 ${userpath}/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.XX.XX //宿主机服务器IP
cluster-announce-port ${PORT}
cluster-announce-bus-port 1${PORT}
appendonly yes
cluster-announce-ip 为宿主机服务器IP
创建redis配置文件
在redis-cluster目录下创建并执行批处理命令,用于创建redis配置文件。
创建端口号为从7000 到 7005 的配置文件
for port in seq 7000 7005
; do
mkdir -p ./KaTeX parse error: Undefined control sequence: \ at position 13: {port}/conf \̲ ̲ && PORT={port} envsubst < ./redis-cluster.tmpl > ./KaTeX parse error: Undefined control sequence: \ at position 24: …onf/redis.conf \̲ ̲ && mkdir -p .…{port}/data;
done
创建redis集群的Docker network
docker network create redis-net
启动Redis容器
将以下批处理命令中${userpath}替换成你的真实路径。执行批处理命令以启动容器。
for port in `seq 7000 7005`; do \
docker run -d -ti -p ${port}:${port} -p 1${port}:1${port} \
-v ${userpath}/redis_cluster/${port}/conf/redis.conf:/usr/local/etc/redis/redis.conf \
-v ${userpath}/redis_cluster/${port}/data:/data \
--restart always --name redis-${port} --net redis-net \
--sysctl net.core.somaxconn=1024 redis:tag redis-server /usr/local/etc/redis/redis.conf; \
done
搭建集群
查看集群网络中的容器ip地址
可以逐个查看
查看7000~7005这6个redis容器的IP,命令行如下:
docker inspect redis7000 | grep IPAddress
查询结果如下:
[root@localhost ~]# docker inspect redis7000 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "192.168.0.2",
[root@localhost ~]#
[root@localhost ~]# docker inspect redis7001 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "192.168.0.3",
[root@localhost ~]#
[root@localhost ~]# docker inspect redis7002 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "192.168.0.4",
[root@localhost ~]#
[root@localhost ~]# docker inspect redis7003 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "192.168.0.5",
[root@localhost ~]# docker inspect redis7004 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "192.168.0.6",
[root@localhost ~]#
[root@localhost ~]# docker inspect redis7005 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.7",
[root@localhost ~]#
也可以使用批处理命令查看IP列表
for port in `seq 7000 7005`; do \
echo -n "$(docker inspect --format '{{ (index .NetworkSettings.Networks "redis-net").IPAddress }}' "redis-${port}")":${port} ' ' ; \
done
得到如下几个ip端口列表:
192.168.0.2:7000 192.168.0.3:7001 192.168.0.4:7002 192.168.0.5:7003 192.168.0.6:7004 192.168.0.7:7005
创建集群
Redis 5.0版本开始,搭建集群已经不再使用ruby了,而是直接使用redis-cli来创建集群。
进入其中一个Redis容器。
docker exec -it redis-7005 /bin/bash
在docker容器内执行集群命令,注意需要用到上一步得到的IP地址。
redis-cli --cluster create 192.168.0.2:7000 192.168.0.3:7001 192.168.0.4:7002 192.168.0.5:7003 192.168.0.6:7004 192.168.0.7:7005 --cluster-replicas 1