Problem with postgres in kubernetes when using password in configMap or secret

1/30/2022

When I deploy postgres like the following everything is ok:

.
.
.
  env:
     - name: POSTGRES_USER
       value: a
.
.
.

But when I deploy it by configMap or secret for example:

        env:
          - name: POSTGRES_USER
            valueFrom:
              secretKeyRef:
                name: postgres
                key: username

when I execute psql -U a it returns: psql: error: could not connect to server: FATAL: role "a" does not exist

I checked environment POSTGRES_USER and this variable is set to a

-- Mohsen R
kubernetes
postgresql

1 Answer

1/30/2022

Accordingly to the documentation from the PostgreSQL image:

The only variable required is POSTGRES_PASSWORD, the rest are optional.

You're defining a custom role, which is okay but you're not passing the POSTGRES_PASSWORD which is mandatory. It's possible the role is not created at all if you don't pass the password.

Another important comment from the documentation:

Warning: the Docker specific variables will only have an effect if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup.

If this is not a playground/stateless environment and you're loading existing data, the startup script won't look at the environment variables and you should use credentials that were previously configured.

-- Erico
Source: StackOverflow