Docker搭建redis-cluster

2020-08-08 10:14:57

主要內容來自:https://www.cnblogs.com/xuchen0117/p/11678931.html

建立資料夾

mkdir redis-cluster-d
cd redis-cluster-d
vim redis-cluster.tmpl

port ${PORT}
masterauth 123456
requirepass 123456
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
cluster-announce-ip 106.52.41.56
cluster-announce-port ${PORT}
cluster-announce-bus-port 1${PORT}
appendonly yes

(1)port(埠號)
(2)masterauth(設定叢集節點間存取密碼,跟下面 下麪一致)
(3)requirepass(設定redis存取密碼)
(4)cluster-enabled yes(啓動叢集模式)
(5)cluster-config-file nodes.conf(叢集節點資訊檔案)
(6)cluster-node-timeout 5000(redis節點宕機被發現的時間)
(7)cluster-announce-ip(叢集節點的ip,寫主機ip,上面的ip是我隨便寫的)
(8)cluster-announce-port(叢集節點的彙報port)
(9)cluster-announce-bus-port(叢集節點的彙報bus-port)
(10) appendonly yes(開啓aof)

生成節點檔案

設定6個節點,3主3從

for port in `seq 6380 6385`; do \
  mkdir -p ./${port}/conf \
  && PORT=${port} envsubst < ./redis-cluster.tmpl > ./${port}/conf/redis.conf \
  && mkdir -p ./${port}/data; \
done

在这里插入图片描述

建立容器

可以用命令建立

for port in `seq 6380 6385`; do \
docker run -d --net=host \
-v /root/redis-cluster-d/${port}/conf/redis.conf:/etc/redis/redis.conf \
-v /root/redis-cluster-d/${port}/data:/data \
--restart always --name=redis-${port}  redis \
redis-server /etc/redis/redis.conf; \
done

也可以使用docker-compose建立,要麻煩點

vim redis-cluster.yml

version: '3'
services:
  redis:
    image: redis
    ports:
      - "6380:6380"
    container_name: "redis"
    network_mode: "host"
    volumes:
      - "/root/docker/redis/redis-cluster-d/6380/conf/redis.conf:/etc/redis/redis.conf"
      - "/root/docker/redis/redis-cluster-d/6380/data:/data"
      - "/etc/localtime:/etc/localtime:ro"
    command: redis-server /etc/redis/redis.conf

搭建叢集

進入一個redis範例

docker exec -it redis-6380 bash
redis-cli -a 123456 --cluster create 106.52.41.56:6380 106.52.41.56:6381 106.52.41.56.78:6382 106.52.41.56:6383 106.52.41.56:6384 106.52.41.56:6385 --cluster-replicas 1

如果在箭頭等待,要把伺服器的安全組的埠放開,包括6380-6385、16380-16385
在这里插入图片描述

驗證

redis-cli -c -a 123456  -p 6380

在这里插入图片描述

#批次停止
docker ps -a | grep -i "redis-*" | awk '{print $1}' | xargs docker stop
#批次刪除
docker ps -a | grep -i "redis-*" | awk '{print $1}' | xargs docker rm -f