背景
redis作为缓存,生产中都是使用集群部署,故开发的时候自己搞了个乞丐版集群。
Docker version 25.0.4
Docker Compose version v2.24.7
redis 7.0
目录结构
project-directory/
├── docker-compose.yml
├── config/
│ ├── redis-node-1.conf
│ ├── redis-node-2.conf
│ └── redis-node-3.conf
└── data/
├── redis-node-1/
├── redis-node-2/
└── redis-node-3/
准备redis配置文件
mkdir -p /data/redis
cd /data/redis
xml
vi config/redis-node-1.conf
port 7000
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
appendonly yes
bind 0.0.0.0
protected-mode no
#requirepass yourpassword
xml
vi config/redis-node-2.conf
port 7001
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
appendonly yes
bind 0.0.0.0
protected-mode no
#requirepass yourpassword
xml
vi config/redis-node-3.conf
port 7002
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
appendonly yes
bind 0.0.0.0
protected-mode no
#requirepass yourpassword
准备 docker-compose.yml 配置文件
xml
version: "3.9"
services:
redis-node-1:
image: redis:7.0
container_name: redis-node-1
command: ["redis-server", "/usr/local/etc/redis/redis.conf", "--cluster-enabled", "yes", "--cluster-config-file", "nodes.conf", "--cluster-node-timeout", "5000", "--appendonly", "yes"]
ports:
- "7000:7000"
volumes:
- ./data/redis-node-1:/data
- ./config/redis-node-1.conf:/usr/local/etc/redis/redis.conf
networks:
- redis-cluster-network
redis-node-2:
image: redis:7.0
container_name: redis-node-2
command: ["redis-server", "/usr/local/etc/redis/redis.conf", "--cluster-enabled", "yes", "--cluster-config-file", "nodes.conf", "--cluster-node-timeout", "5000", "--appendonly", "yes"]
ports:
- "7001:7001"
volumes:
- ./data/redis-node-2:/data
- ./config/redis-node-2.conf:/usr/local/etc/redis/redis.conf
networks:
- redis-cluster-network
redis-node-3:
image: redis:7.0
container_name: redis-node-3
command: ["redis-server", "/usr/local/etc/redis/redis.conf", "--cluster-enabled", "yes", "--cluster-config-file", "nodes.conf", "--cluster-node-timeout", "5000", "--appendonly", "yes"]
ports:
- "7002:7002"
volumes:
- ./data/redis-node-3:/data
- ./config/redis-node-3.conf:/usr/local/etc/redis/redis.conf
networks:
- redis-cluster-network
networks:
redis-cluster-network:
driver: bridge
拉取镜像并启动redis
docker-compose up -d
查看redis容器
docker ps | grep redis
查看每个容器的IP地址
docker inspect redis-node-1 | grep IPAddress
同理:将其他容器的IP一一查出。
创建集群
docker exec -it redis-node-1 redis-cli --cluster create \ 172.19.0.3:7000 172.19.0.2:7001 172.19.0.4:7002 \ --cluster-replicas 0
这里的IP就是上一步查出的,要注意对应容器IP和端口要写对,要和docker-compose.yml配置的内容对上。
这里没有从节点,如果你想添加从节点,语法如下:docker exec -it redis-node-1 redis-cli --cluster create
<主节点IP>:7000 <主节点IP>:7001 <主节点IP>:7002
<从节点IP>:7003 <从节点IP>:7004 <从节点IP>:7005
--cluster-replicas 1
测试redis
进入容器并登录redis
docker exec -it redis-node-1 redis-cli -c -p 7000
查看集群信息
cluster nodes
cluster info
关闭集群
docker-compose stop
开启集群
docker-compose start