Docker部署Redis集群

https://www.bilibili.com/video/BV1og4y1q7M4?p=40&spm_id_from=pageDriver 跟着狂神视频搭建,做哈记录23333

需要搭建的效果如图::三个主机分别都有一台从机,当某个主机驾崩了,他的从机会自动上位
Docker部署Redis集群_第1张图片
1)执行如下脚本配置环境和启动容器

#通过脚本一次创建6个redis配置
for port in $(seq 1 6); \
do \
mkdir -p /mydata/redis/node-${port}/conf
touch /mydata/redis/node-${port}/conf/redis.conf
cat << EOF >/mydata/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
# 通过脚本一次启动6个redis容器
docker run -p 637${port}:6379 -p 1637${port}:16379 --name redis-${port} \
-v /mydata/redis/node-${port}/data:/data \
-v /mydata/redis/node-${port}/conf/redis.conf:/etc/redis/redis.conf \
-d --net redis --ip 172.38.0.1${port} redis:5.0.9-alpine3.11 redis-server /etc/redis/redis.conf
done

结果如下:
Docker部署Redis集群_第2张图片

//进入redis中
[root@us4ci6jaxom1jjz2 redis]# docker exec -it redis-1 /bin/sh   
/data # ls
appendonly.aof  nodes.conf

//创建集群
/data # redis-cli --cluster create 172.38.0.11:6379 172.38.0.12:6379 172.38.0.13:6379 172.38.0.14:6379 172.38.0.15:6379 172.38.0.16:6379 --cluster-replicas 1   
>>> Performing hash slots allocation on 6 nodes...
Master[0] -> Slots 0 - 5460
Master[1] -> Slots 5461 - 10922
Master[2] -> Slots 10923 - 16383
Adding replica 172.38.0.15:6379 to 172.38.0.11:6379
Adding replica 172.38.0.16:6379 to 172.38.0.12:6379
Adding replica 172.38.0.14:6379 to 172.38.0.13:6379
....

//进入集群
/data # redis-cli -c
127.0.0.1:6379> cluster info    //查看集群信息
cluster_state:ok
...
127.0.0.1:6379> cluster nodes   //查看集群节点
f89c10ffeca9973700d4dd38ef87a1d4f8967a2b 172.38.0.11:6379@16379 myself,master - 0 1649554715000 1 connected 0-5460
96ae9d27a5a5b442c2d7ece2f4d6b3f16c4b837d 172.38.0.13:6379@16379 master - 0 1649554715000 3 connected 10923-16383
5c2ee2a7391f03d91505aa2269be1f30396afbca 172.38.0.15:6379@16379 slave f89c10ffeca9973700d4dd38ef87a1d4f8967a2b 0 1649554714537 5 connected
89145c5054f30a7bd0b247936cb2f8bea0333136 172.38.0.14:6379@16379 slave 96ae9d27a5a5b442c2d7ece2f4d6b3f16c4b837d 0 1649554715000 4 connected
dc026be935a99ee8c1e39d24a0dbf58b1ecc2d54 172.38.0.12:6379@16379 master - 0 1649554715840 2 connected 5461-10922
70614a4e70c05940cc253194e99595b33bdf458d 172.38.0.16:6379@16379 slave dc026be935a99ee8c1e39d24a0dbf58b1ecc2d54 0 1649554715000 6 connected


//集群测试
/*
在当前机子上set一个值,然后重开一个连接把当前这个容器stop,在回过来get值发现被阻塞,退出,重新连接,再次get获取到了值
此时连接重定向,连接换成了他的从机,cluster nodes查看节点信息,发现宕掉的redis和他的slave变成了主机)*/
127.0.0.1:6379> set a b   
-> Redirected to slot [15495] located at 172.38.0.13:6379 OK
172.38.0.13:6379> get a
^C
/data # redis-cli -c
127.0.0.1:6379> get a
-> Redirected to slot [15495] located at 172.38.0.14:6379
"b"
172.38.0.14:6379>   //连接变了
172.38.0.14:6379> cluster nodes  //查看节点信息,可以发现13挂了,14成为了从机

在这里插入图片描述

你可能感兴趣的:(tool,docker)