使用docker-compose搭建redis+sentinel集群
redis版本:6.2.4,docker-compose版本:1.25.1,虚拟机:192.168.1.211
redis集群:6379,6380,6381
sentinel集群:26379,26380,26381
1. docker-compose的安装
(1)下载
curl -L https://github.com/docker/compose/releases/download/1.24.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
(2)添加权限
chmod +x /usr/local/bin/docker-compose
(3)查看版本
docker-compose --version
2. 配置redis
(0)层级结构
(1)新建目录redis
mkdir redis
(2)编写docker-compose.yml
version: '3.4'
image: redis:6.2.4
container_name: redis-master
restart: always
ports:
- 6379:6379
command: redis-server --port 6379 --requirepass 123456 --masterauth 123456 --appendonly yes
#network_mode: "host"
container_name: redis-slave1
restart: always
ports:
- 6380:6380
command: redis-server --slaveof redis-master 6379 --port 6380 --requirepass 123456 --masterauth 123456 --appendonly yes
#network_mode: "host"
slave2:
image: redis:6.2.4
container_name: redis-slave2
restart: always
ports:
- 6381:6381
command: redis-server --slaveof redis-master 6379 --port 6381 --requirepass 123456 --masterauth 123456 --appendonly yes
#network_mode: "host"
(3)在docker-compose.yml同级目录下启动redis
docker-compose up -d
(4)查看redis启动状态
ps -ef | grep redis
3. 测试redis主从
(1)进入master容器并设置值
docker exec -it redis-master redis-cli
auth 123456
set a a
(2)进入slave容器查看是否同步
docker exec -it redis-slave1 redis-cli -p 6380
auth 123456
get a
4. 配置sentinel
(1)在redis文件夹下新建目录
cd redis
mkdir sentinel
(2)创建docker-compose.yml
version: '3'
services:
sentinel1:
image: redis:6.2.4
container_name: sentinel-master
ports:
- 26379:26379
command: redis-sentinel /app/redis/sentinel.conf
volumes:
- ./sentinel1.conf:/app/redis/sentinel.conf
sentinel2:
image: redis:6.2.4
container_name: sentinel-slave1
ports:
- 26380:26380
command: redis-sentinel /app/redis/sentinel.conf
volumes:
- ./sentinel2.conf:/app/redis/sentinel.conf
sentinel3:
image: redis:6.2.4
container_name: sentinel-slave2
ports:
- 26381:26381
command: redis-sentinel /app/redis/sentinel.conf
volumes:
- ./sentinel3.conf:/app/redis/sentinel.conf
networks:
default:
external:
name: redis_default
(3)创建sentinel.conf配置文件
三个sentinel.conf配置文件内容,只需更改对应的端口即可,其余不变
port 26379 # sentinel1:26379,sentinel2:26380,sentinel3:26381
dir /tmp
sentinel monitor mymaster 172.18.0.4 6379 2
sentinel auth-pass mymaster 123456
sentinel down-after-milliseconds mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 180000
sentinel deny-scripts-reconfig yes
说明:sentinel monitor mymaster 192.168.8.150 6379 2,IP可使用docker inspect redis-master查看
(4)启动sentinel
进入sentinel文件夹
docker-compose up -d
5. 测试sentinel主备切换
(1)分别进入三个redis容器中
进入master容器:
docker exec -it redis-master redis-cli
auth 123456
info replication
进入slave容器:
docker exec -it redis-slave1 redis-cli -p 6380
auth 123456
info replication
(2)停止master
在master容器执行SHUTDOWN或者执行docker stop redis-master
(3)观察主备切换
docker logs -f sentinel-master
master切换到redis-slave2了