Redis StatefulSet Example

In this example, a ConfigMap redis-config is created with a custom Redis configuration file. A Secrets redis-secret is created with the Redis password. The StatefulSet redis-statefulset is then created, which uses the Redis image, sets the password as an environment variable, and mounts the ConfigMap as a volume at /usr/local/etc/redis/redis.conf. This means that the Redis container will use the custom configuration and password when it starts up.

apiVersion: v1
kind: ConfigMap
metadata:
  name: redis-config
data:
  redis.conf: |
    bind 0.0.0.0
    protected-mode no
apiVersion: v1
kind: Secret
metadata:
  name: redis-secret
data:
  REDIS_PASSWORD: cGFzc3dvcmQ=

Finally, create and apply the StatefulSet:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis-statefulset
spec:
  serviceName: redis
  replicas: 1
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - name: redis
        image: redis
        ports:
        - containerPort: 6379
        env:
        - name: REDIS_PASSWORD
          valueFrom:
            secretKeyRef:
              name: redis-secret
              key: REDIS_PASSWORD
        volumeMounts:
        - name: config-volume
          mountPath: /usr/local/etc/redis/redis.conf
          subPath: redis.conf
      volumes:
      - name: config-volume
        configMap:
          name: redis-config