kubernetes启动redis并设置密码yaml文件

测试环境创建redis单机就可以满足,redis启动后默认是无密码的,为了安全我们会登录容器手动设置,但是容器重启后又出现无密码,所以希望redis 容器启动后自动设置密码:
docker启动redis并设置密码:

$ docker run -d --name redis -p 6379:6379 redis --requirepass "PASSWORD"

修改redis 密码这里有两种法式:
配置redis.conf,利用kubernetes 的配置管理configmap,然后挂载到容器的相应路径,然后指定配置文件启动:redis-server /path/redis.conf,或者基于官方镜像再打镜像,Dockerfile如下:

FROM redis
COPY redis.conf /usr/local/etc/redis/redis.conf
CMD [ "redis-server", "/usr/local/etc/redis/redis.conf" ]

另一种是利用kubernetes的lifecycle.postStart设置redis密码,这种方法简单方便,下面就是用kubernetes的lifecycle.postStart设置redis密码。
kubernetes启动redis并设置密码yaml文件:

$ cat redis.yaml 
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis
  namespace: test
spec:
  podManagementPolicy: Parallel
  serviceName: redis
  replicas: 1
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - name: redis
        image: redis
        lifecycle:
          postStart:
            exec:
              command: [ "/bin/sh", "-c", "redis-cli config set requirepass Kjgnj93JKj3je" ]
        ports:
        - containerPort: 6379
        resources:
          limits:
            cpu: 1
            memory: 1Gi
          requests:
            cpu: 0.5
            memory: 500Mi
        volumeMounts:
        - name: redis
          mountPath: /data
      volumes:
        - name: redis
          persistentVolumeClaim:
            claimName: redis

redis service yaml文件:

$ cat redis-service.yaml 
apiVersion: v1
kind: Service
metadata:
  namespace: test
  name: redis
  labels:
    app: redis
spec:
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    app: redis