部署redis集群

  1. Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
FROM alpine:latest
MAINTAINER lifei

#换源
RUN echo 'http://mirrors.ustc.edu.cn/alpine/edge/main' > /etc/apk/repositories
RUN echo '@community http://mirrors.ustc.edu.cn/alpine/edge/community' >> /etc/apk/repositories
RUN echo '@testing http://mirrors.ustc.edu.cn/alpine/edge/testing' >> /etc/apk/repositories

RUN apk update

# 修正时区
ENV TIMEZONE Asia/Shanghai
RUN apk add tzdata
RUN ln -snf /usr/share/zoneinfo/$TIMEZONE /etc/localtime
RUN echo $TIMEZONE > /etc/timezone

#修改一些系统设置
RUN echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
RUN echo "echo never > /sys/kernel/mm/transparent_hugepage/enabled" >> /etc/rc.local

#开始安装 redis
RUN apk add redis
COPY start_redis.sh /usr/local/
RUN chmod +x /usr/local/start_redis.sh
RUN chown redis:redis /usr/local/start_redis.sh

EXPOSE 6379

ENTRYPOINT ["sh","/usr/local/start_redis.sh"]
CMD ["master"]
  1. start_redis.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
redis_role=$1
sed -i 's/protected-mode yes/protected-mode no/g' /etc/redis.conf
sed -i 's/daemonize yes/daemonize no/g' /etc/redis.conf
sed -i 's/bind 127.0.0.1/bind 0.0.0.0/g' /etc/redis.conf

echo "Start Redis by "
if [ $redis_role = "master" ]; then
echo "master"
redis-server /etc/redis.conf
elif [ $redis_role = "slave" ]; then
echo "slave"
sed -i 's/# slaveof <masterip> <masterport>/slaveof redis-master 6379/g' /etc/redis.conf
redis-server /etc/redis.conf
else
echo "unknow role!"
fi
  1. 在上面的目录下
1
2
3
4
5
6
7
8
9
10
11
docker run -d --name=redis-master -p=6379:6379 lifei2199/redis master
docker run -d --name=node1 --link=redis-master:redis-master -p=7001:6379 lifei2199/redis slave
docker run -d --name=node2 --link=redis-master:redis-master -p=7002:6379 lifei2199/redis slave
docker run -d --name=node3 --link=redis-master:redis-master -p=7003:6379 lifei2199/redis slave
docker ps -a

docker exec -i redis-master /bin/sh
redis-cli
info replication
set username lifei2199
get username
  1. 关闭
1
2
3
4
5
6
7
8
停用全部运行中的容器:
docker stop $(docker ps -q)

删除全部容器:
docker rm $(docker ps -aq)

一条命令实现停用并删除容器:
docker stop $(docker ps -q) & docker rm $(docker ps -aq)