Solution

2 minutes read
  1. The password we want to store in the Secret is dbpass.

First, we encode this password in base64:

$ echo -n "dbpass" | base64
ZGJwYXNz

Next, we create the following file defining a Secret:

apiVersion: v1
kind: Secret
metadata:
  name: db
data:
  password: ZGJwYXNz
  1. We modify the db Deployment specification to reference the contents of the Secret key password instead of using the password in plain text:
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: db
  name: db
spec:
  replicas: 1
  selector:
    matchLabels:
      app: db
  template:
    metadata:
      labels:
        app: db
    spec:
      containers:
        - image: postgres:15.1-alpine3.17
          name: postgres
          env:
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db
                  key: password
          ports:
            - containerPort: 5432
              name: postgres
  1. We modify the worker and result Deployments (the two microservices connecting to db) to add the POSTGRES_PASSWORD environment variable, which retrieves its value from the db Secret.

The new worker Deployment specification:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: worker
  name: worker
spec:
  replicas: 1
  selector:
    matchLabels:
      app: worker
  template:
    metadata:
      labels:
        app: worker
    spec:
      containers:
        - image: voting/worker:latest
          name: worker
          env:
          - name: POSTGRES_PASSWORD
            valueFrom:
              secretKeyRef:
                name: db
                key: password

The new result Deployment specification:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: result
  name: result
spec:
  replicas: 1
  selector:
    matchLabels:
      app: result
  template:
    metadata:
      labels:
        app: result
    spec:
      containers:
        - image: voting/result:latest
          name: result
          env:
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db
                  key: password
  1. We deploy the application with the following command from the manifests directory:
kubectl apply -f .

As before, using the IP address of one of the cluster nodes, we can access the voting and result interfaces via ports 31000 and 31001, respectively.

  1. We delete the application with the following command from the manifests directory:
kubectl delete -f .