Search code examples
postgresqldockervariablesconfig

Use Environment Variables to PostgreSQL Config File postgresql.conf


I have a custom DockerFile that build PostgreSQL with multiple extensions which are required from our software. Below is a sample of this DockerFile:

FROM postgres:15.4

# Update System
RUN apt-get update

WORKDIR /

#system preloaded libraries
RUN echo "shared_preload_libraries='pglogical,pg_cron'" >> /usr/share/postgresql/postgresql.conf.sample
#cron default database
RUN echo "cron.database_name=postgres" >> /usr/share/postgresql/postgresql.conf.sample

The above "RUN" commands are patching the postgresql.conf.sample file by adding some additional parameters (like cron.database_name=postgres) which are used by pg_cron extension to operate.

What if i want to make these parameters look into variable so then be able to change it from docker-compose or from kubernetes ConfigMap?

For example I tried this configuration:

FROM postgres:15.4

# Update System
RUN apt-get update

WORKDIR /

#system preloaded libraries
RUN echo "shared_preload_libraries='pglogical,pg_cron'" >> /usr/share/postgresql/postgresql.conf.sample
#cron default database
RUN echo "cron.database_name=$CRON_DATABASE_NAME" >> /usr/share/postgresql/postgresql.conf.sample

The above code produces this line in the end of the postgresql.conf file

cron.database_name=$CRON_DATABASE_NAME

instead of this line

cron.database_name=postgres

But postgres fails to start because seems it cannot understand $CRON_DATABASE_NAME as variable

On the other side seems that by setting the WAL_LEVEL environment variable works without being at all into postgresql.conf which is not the case for this additional parameter cron.database_name

Any ideas?


Solution

  • I found out that only some variables can be used as environment variables and those are the "postmaster" variables. These variables are flagged with "postmaster" flag into postgresql documentation.

    environment:
       -pgdata=/var/lib/postgresql/data/pgdata
       -wal_level=logical
    

    On the other side to set variables on postgresql startup (postmaster or not) like tuning parameters we can use the following code like arguments into docker compose or kubernetes stateful-set.

    args:
       -c cron.database_name=postgres
       -c min_wal_size=1GB
       -c max_wal_size=4GB
    

    The only issue is that we need to restart postgres to take effect.