Search code examples
postgresqldockerkubernetesskaffold

Setting postgres environmental variables running image


As the documentation shows, you should be setting the env vars when doing a docker run like the following:

docker run --name some-postgres -e POSTGRES_PASSWORD='foo' POSTGRES_USER='bar'

This sets the superuser and password to access the database instead of the defaults of POSTGRES_PASSWORD='' and POSTGRES_USER='postgres'.

However, I'm using Skaffold to spin up a k8s cluster and I'm trying to figure out how to do something similar. How does one go about doing this for Kubernetes and Skaffold?


Solution

  • @P Ekambaram is correct but I would like to go further into this topic and explain the "whys and hows".

    When passing passwords on Kubernetes, it's highly recommended to use encryption and you can do this by using secrets.

    Creating your own Secrets (Doc)

    To be able to use the secrets as described by @P Ekambaram, you need to have a secret in your kubernetes cluster.

    To easily create a secret, you can also create a Secret from generators and then apply it to create the object on the Apiserver. The generators should be specified in a kustomization.yaml inside a directory.

    For example, to generate a Secret from literals username=admin and password=secret, you can specify the secret generator in kustomization.yaml as

    # Create a kustomization.yaml file with SecretGenerator
    $ cat <<EOF >./kustomization.yaml
    secretGenerator:
    - name: db-user-pass
      literals:
      - username=admin
      - password=secret
    EOF
    

    Apply the kustomization directory to create the Secret object.

    $ kubectl apply -k .
    secret/db-user-pass-dddghtt9b5 created
    

    Using Secrets as Environment Variables (Doc)

    This is an example of a pod that uses secrets from environment variables:

    apiVersion: v1
    kind: Pod
    metadata:
      name: secret-env-pod
    spec:
      containers:
      - name: mycontainer
        image: redis
        env:
          - name: SECRET_USERNAME
            valueFrom:
              secretKeyRef:
                name: mysecret
                key: username
          - name: SECRET_PASSWORD
            valueFrom:
              secretKeyRef:
                name: mysecret
                key: password
      restartPolicy: Never
    

    Source: here and here.