基于Docker搭建redis-cluster

# 安装docker
yum install docker
systemctl start docker

# 下载redis5.0.5镜像
docker pull redis:5.0.5

# 编写实现文件
cd /home
mkdir redis-cluster
cd redis-cluster
vim redis-cluster.tmpl

# 填入以下内容
port ${PORT}
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
# 这里填写宿主机IP,阿里云用公网IP时集群创建会失败,内网IP没问题
cluster-announce-ip x.x.x.x
cluster-announce-port ${PORT}
cluster-announce-bus-port 1${PORT}
appendonly yes
requirepass test@123

# 构建redis网络
docker network create redis-net
docker network ls

# 执行上面的tmpl文件,传入参数 8000 - 8005 作为redis不同单节点的端口
for port in `seq 8000 8005`; do \
mkdir -p ./${port}/conf \
&& PORT=${port} envsubst < ./redis-cluster.tmpl > ./${port}/conf/redis.conf \
&& mkdir -p ./${port}/data; \
done

# 授权 文件夹 权限
chmod 777 8000 8001 8002 8003 8004 8005

# 启动docker redis镜像  将会启动 8000 8001 8002 8003 8004 8005五个节点的redis
for port in `seq 8000 8005`; do \
docker run -d -ti -p ${port}:${port} -p 1${port}:1${port} \
--privileged=true \
-v /home/redis-cluster/${port}/conf/redis.conf:/usr/local/etc/redis/redis.conf \
-v /home/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

# 查看 IP 及 端口 (docker内网)
for port in `seq 8000 8005`; do \
echo -n "$(docker inspect --format '{{ (index .NetworkSettings.Networks "redis-net").IPAddress }}' "redis-${port}")":${port}"  "  ; \
done
# 回显
172.18.0.2:8000  172.18.0.3:8001  172.18.0.4:8002  172.18.0.5:8003  172.18.0.6:8004  172.18.0.7:8005 

#进入redis-8000容器
docker exec -it redis-8000 bash
# 设置三主三从
redis-cli -a test@123 --cluster create 172.18.0.2:8000 172.18.0.3:8001 172.18.0.4:8002 172.18.0.5:8003 172.18.0.6:8004 172.18.0.7:8005 --cluster-replicas 1
#遇到提示输入 yes

# 遇到等待join需要新开一个ss窗口执行以下命令如果成功了,就不用了
#分别进入 其他redis容器 加入 8000 的集群中
docker exec -it redis-8001 bash
redis-cli -a test@123 -p 8001 cluster meet 172.18.0.2 8000
exit
 
docker exec -it redis-8002 bash
redis-cli -a test@123 -p 8002 cluster meet 172.18.0.2 8000
exit

docker exec -it redis-8003 bash
redis-cli -a test@123 -p 8003 cluster meet 172.18.0.2 8000
exit
 
docker exec -it redis-8004 bash
redis-cli -a test@123 -p 8004 cluster meet 172.18.0.2 8000
exit
 
docker exec -it redis-8005 bash
redis-cli -a test@123 -p 8005 cluster meet 172.18.0.2 8000
exit

# 查看redis-cluster
docker exec -it redis-8000 bash
redis-cli -a test@123 -p 8000 cluster nodes