自学内容网 自学内容网

Docker Compose 搭建 Redis 主从复制

服务器状态

IP PORTROLE
192.168.142.1576379master
192.168.142.1566390slave
192.168.142.1556391slave02

master

docker-compose.yml

services:
  redis-master:
    image: hub.atomgit.com/amd64/redis:7.0.13
    restart: always
    container_name: redis-master
    privileged: true
    ports:
      - '6379:6379'
    volumes:
      - redis-data:/opt/bitnami/redis/data
      - /root/redis.conf:/etc/redis.conf
      - /etc/localtime:/etc/localtime:ro
    command:
      - /bin/sh
      - -c
      - redis-server /etc/redis.conf
volumes:
  redis-data:

redis.conf

daemonize no
port 6379
protected-mode no
bind 0.0.0.0
requirepass 123456

slave

docker-compose.yml

services:
  redis-slave:
    image: hub.atomgit.com/amd64/redis:7.0.13
    restart: always
    container_name: redis-slave
    privileged: true
    ports:
      - '6390:6379'
    volumes:
      - redis-data:/opt/bitnami/redis/data
      - /root/redis.conf:/etc/redis.conf
      - /etc/localtime:/etc/localtime:ro
    command:
      - /bin/sh
      - -c
      - redis-server /etc/redis.conf
volumes:
  redis-data:

redis.conf

daemonize no
port 6390
protected-mode no
masterauth 123456
requirepass 123456
slave-read-only yes
bind 0.0.0.0
slaveof 192.168.142.157 6379

slave02

docker-compose.yml

services:
  redis-slave02:
    image: hub.atomgit.com/amd64/redis:7.0.13
    restart: always
    container_name: redis-slave02
    privileged: true
    ports:
      - '6391:6379'
    volumes:
      - redis-data:/opt/bitnami/redis/data
      - /root/redis.conf:/etc/redis.conf
      - /etc/localtime:/etc/localtime:ro
    command:
      - /bin/sh
      - -c
      - redis-server /etc/redis.conf
volumes:
  redis-data:

redis.conf

daemonize no
port 6391
protected-mode no
masterauth 123456
requirepass 123456
slave-read-only yes
bind 0.0.0.0
slaveof 192.168.142.157 6379

启动 docker

docker compose up -d

查看主从状态

master

docker exec -it redis-master redis-cli -a 123456 -c info replication

slave

docker exec -it redis-slave redis-cli -a 123456 -p 6390 -c info replication

结果

master

# Replication
role:master
connected_slaves:2
slave0:ip=192.168.142.156,port=6390,state=online,offset=84,lag=1
slave1:ip=192.168.142.155,port=6391,state=online,offset=84,lag=1

slave

# Replication
role:slave
master_host:192.168.142.157
master_port:6379
master_link_status:up

插入数据测试

master

root@master:~# docker exec -it redis-master redis-cli -a 123456 -c set HQ 123
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
OK

slave

root@slave:~# docker exec -it redis-slave redis-cli -a 123456 -p 6390 -c get HQ
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
"123"

总而言之最总要的一步就是 slaveof <主服务IP>  <主服务端口>


原文地址:https://blog.csdn.net/qq_62866151/article/details/142387885

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!