拉取redis镜像

1
docker pull redis:5.0.3

增加配置文件redis-cluster.tmpl

在用户目录下创建文件 ${userpath}/redis-cluster/redis-cluster.tmpl

1
2
3
4
5
6
7
8
9
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 ./${port}/conf
&& PORT=${port} envsubst < ./redis-cluster.tmpl > ./${port}/conf/redis.conf
&& mkdir -p ./${port}/data;
done

创建redis集群的Docker network

1
docker network create redis-net

启动Redis容器

将以下批处理命令中${userpath}替换成你的真实路径。执行批处理命令以启动容器。

1
2
3
4
5
6
7
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,命令行如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 docker inspect redis7000 | grep IPAddress
```
查询结果如下:
```text
[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列表

1
2
3
for port in `seq 7000 7005`; do \
echo -n "$(docker inspect --format '{{ (index .NetworkSettings.Networks "redis-net").IPAddress }}' "redis-${port}")":${port} ' ' ; \
done

得到如下几个ip端口列表:

1
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容器。

1
docker exec -it redis-7005 /bin/bash

在docker容器内执行集群命令,注意需要用到上一步得到的IP地址。

1
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