用docker stack开启redis集群
(金庆的专栏 2017.10)
有5个docker swarm节点,开启redis cluster.
每个机器上开2个redis节点,共10个redis节点。
采用官方的redis:alpine镜像。
docker-stack.yml 如下:
version: "3"
services:
redis001:
image: redis:alpine
volumes:
- /home/redis/001/data:/data
- /home/redis/001/conf:/conf
command: redis-server --appendonly yes --cluster-enabled yes --cluster-config-file /conf/nodes.conf --cluster-announce-ip 10.240.79.8 --cluster-announce-port 7001 --cluster-announce-bus-port 17001
ports:
- "7001:6379"
- "17001:16379"
networks:
- redisnet
deploy:
placement:
constraints:
- node.hostname == host-10-240-79-8
redis002:
image: redis:alpine
volumes:
- /home/redis/002/data:/data
- /home/redis/002/conf:/conf
command: redis-server --appendonly yes --cluster-enabled yes --cluster-config-file /conf/nodes.conf --cluster-announce-ip 10.240.79.9 --cluster-announce-port 7002 --cluster-announce-bus-port 17002
ports:
- "7002:6379"
- "17002:16379"
networks:
- redisnet
deploy:
placement:
constraints:
- node.hostname == host-10-240-79-9
redis003:
...
redis010:
...
networks:
redisnet:
数据保存文件在 /home/redis/001/data
集群配置文件将保存到 /home/redis/001/conf/nodes.conf
各机器上目录需要预先创建,不然docker开启失败。
并且需要设置目录权限,不然报"Permission denied".
redis-server以用户uid=100(redis)运行,所以
chown -R 100 /home/redis/
启动redis服务栈:
docker stack deploy -c docker-stack.yml redis
redis-server启动后,运行 redis-trib.rb 来组建 redis cluster:
docker run --rm -it inem0o/redis-trib create --replicas 1 10.240.79.8:7001 10.240.79.9:7002 ... 10.240.79.12:7010
注意 inem0o/redis-trib 的说明中,命令示例缺少 "-it", 会报错退出:
Can I set the above configuration? (type 'yes' to accept): : undefined method `chomp' for nil:NilClass (NoMethodError)
from /usr/bin/redis-trib:1295:in `create_cluster_cmd'
from /usr/bin/redis-trib:1701:in `<main>'
运行 redis-cli 测试,"-c" 参数表示集群,可连接任意机器的7001-7010任意端口:
[root@host-10-240-79-9 ~]# docker run -it --rm redis:alpine redis-cli -h 10.240.79.8 -p 7006 -c
10.240.79.8:7006> get a
-> Redirected to slot [15495] located at 10.240.79.10:7003
(nil)
用swarm mode开启redis服务比较方便。
但是出于性能考虑,应该禁用 swarm 的NAT转发和负载均衡。
研究了下,暂时还没学会。