简体   繁体   中英

postgres with custom pg_hba.conf at startup

I am using postgres14 inside docker-container. I want my DB to start with custom pg_hba.conf so I created my own dockerfile that adds 1 file to official postgres14 image:

FROM postgres:14.2
COPY pg_hba.conf /ftool/

Now, after building above dockerfile I have following error during start of container:

initdb: error: directory "/ftool" exists but is not empty
If you want to create a new database system, either remove or empty
the directory "/ftool" or run initdb
with an argument other than "/ftool".

How do I inject my pg_hba.conf before DB gets initialized?

The Postgres README on Docker Hub discusses this. You can create a shell script to do additional initialization work. See below for that.

For simpler pg_hba.conf

If your pg_hba.conf is a pretty simple one, like

host all all all md5

Then you can go with a much easier route by specifying a value for the environment variable POSTGRES_HOST_AUTH_METHOD . It will create a simple pg_hba.conf for you, using the noted auth_method as the final field ( md5 in the above example).

If you require something more complex than that, keep reading below.

Creating a custom script

From https://hub.docker.com/_/postgres :

Initialization scripts

If you would like to do additional initialization in an image derived from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files, run any executable *.sh scripts, and source any non-executable *.sh scripts found in that directory to do further initialization before starting the service.

For example, to add an additional user and database, add the following to /docker-entrypoint-initdb.d/init-user-db.sh:

 #!/bin/bash set -e psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL CREATE USER docker; CREATE DATABASE docker; GRANT ALL PRIVILEGES ON DATABASE docker TO docker; EOSQL

So, to solve your problem, COPY your pg_hba.conf file to some path other than the db directory, and create a script like /docker-entrypoint-initdb.d/pg_hba_setup.sh which copies it to the proper path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM