k8s 部署 redis 集群

redis-master

redis-master.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-master
  labels:
    name: redis-master

spec:
  replicas: 1
  selector:
    matchLabels:
      name: redis-master
  template:
    metadata:
      labels:
        name: redis-master
    spec:
      containers:
      - name: master
        image: redis
        ports:
        - containerPort: 6379


---
apiVersion: v1
kind: Service
metadata:
  name: redis-master
  labels:
    name: redis-master

spec:
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    name: redis-master

redis-slave

Dockerfile

FROM redis

COPY run.sh /
RUN chmod +x /run.sh
CMD /run.sh

run.sh

if [[ ${GET_HOSTS_FROM:-dns} == "env" ]]; then
  redis-server --slaveof ${REDIS_MASTER_SERVICE_HOST} 6379
else
  redis-server --slaveof redis-master 6379
fi

docker build 生成镜像

redis-slave.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-slave
  labels:
    name: redis-slave

spec:
  replicas: 2
  selector:
    matchLabels:
      name: redis-slave
  template:
    metadata:
      labels:
        name: redis-slave
    spec:
      containers:
      - name: worker
        image: hitol/redis-slave
        env:
        - name: GET_HOSTS_FROM
          value: env
        ports:
        - containerPort: 6379


---
apiVersion: v1
kind: Service
metadata:
  name: redis-slave
  labels:
    name: redis-slave

spec:
  ports:
  - port: 6379
  selector:
    name: redis-slave

验证

kubectl exec -it redis-master-4m5ds redis-cli 往 redis 里写几条数据,然后切换到 slave pod 里看有没有。

2022/2/27 posted in  kubernetes redis