1.创建网卡
docker network create redis --subnet 172.38.0.0/16
2.通过脚本创建六个redis配置文件
[root@919 ~]# cd /root/redis/
for port in $(seq 1 6);
do
mkdir -p /root/redis/node-${port}/conf
touch /root/redis/node-${port}/conf/redis.conf
cat << EOF >/root/redis/node-${port}/conf/redis.conf
port 6379
bind 0.0.0.0
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 172.38.0.1${port}
cluster-announce-port 6379
cluster-announce-bus-port 16379
appendonly yes
EOF
done
3.编写脚本运行容器
# vim /root/redis/redis.sh
#!/bin/bash
# 创建6个redis容器
ip=172.38.0.1
for port in $(seq 1 6);do
docker run -p 637${port}:6379 -p 1637${port}:16379 --name redis-${port}
-v /root/redis/node-${port}/data:/data
-v /root/redis/node-${port}/conf/redis.conf:/etc/redis/redis.conf
-d --net redis --ip ${ip}${port} redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
done
4.创建集群
/data # redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.1
3:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379 --cluster-replicas 1
5.查看集群信息
/data # redis-cli -c #-c cluster 连接集群
127.0.0.1:6379> CLUSTER INFO
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6
cluster_size:3
cluster_current_epoch:6
cluster_my_epoch:1
cluster_stats_messages_ping_sent:242
cluster_stats_messages_pong_sent:224
cluster_stats_messages_sent:466
cluster_stats_messages_ping_received:219
cluster_stats_messages_pong_received:242
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:466
# 三主三从
127.0.0.1:6379> CLUSTER NODES
62a5adba6d061b5e9399137bc302a2a7232423d9 172.38.0.11:6379@16379 myself,master - 0 1600610892000 1 connected 0-5460
12d5d719cac75270d37717f8e88bf1e4b8d7c71f 172.38.0.15:6379@16379 slave 62a5adba6d061b5e9399137bc302a2a7232423d9 0 1600610894223 5 connected
ffff2fdcb0f0823932e7a3a8052edd957068eb8e 172.38.0.12:6379@16379 master - 0 1600610895727 2 connected 5461-10922
6b6c853e7569823049d78e305a6dd1fbd347aaf3 172.38.0.16:6379@16379 slave ffff2fdcb0f0823932e7a3a8052edd957068eb8e 0 1600610895225 6 connected
04a7d213e1203bddf14b13a166fb9d13dc1d0b92 172.38.0.14:6379@16379 slave 20904935a4c115ca4e9aa93c65ef223ed808819d 0 1600610894000 4 connected
20904935a4c115ca4e9aa93c65ef223ed808819d 172.38.0.13:6379@16379 master - 0 1600610894000 3 connected 10923-16383
6.模拟某个redis-master宕机
# set一个值
127.0.0.1:6379> set k1 v1
-> Redirected to slot [12706] located at 172.38.0.13:6379
OK
172.38.0.13:6379> get k1
"v1"
172.38.0.13:6379> exit
# 此时将ip为172.38.0.13的容器stop关闭
/data # read escape sequence
[root@919 redis]# docker stop redis-3
redis-3
# 重新进入容器连接redis
[root@919 redis]# docker exec -it redis-1 /bin/sh
/data # redis-cli -c
127.0.0.1:6379> get k1
-> Redirected to slot [12706] located at 172.38.0.14:6379
"v1"