Reputation: 365
I am trying to start a postgres container form docker-compose file and also initialize it.
docker-compose.yml
version: "3"
postgres:
image: "postgres"
command: bash -c "
postgres &&
createuser -l \"auser\"
"
My goal is: 1) start postgres container 2) create a user
The current implementation fails with the following error
"root" execution of the PostgreSQL server is not permitted.
The server must be started under an unprivileged user ID to prevent
possible system security compromise. See the documentation for
more information on how to properly start the server.
Upvotes: 2
Views: 15655
Reputation: 60084
"root" execution of the PostgreSQL server is not permitted.
You should not run the DB container with root
user. better to run postgres
user.
one way is to specify the user in the docker-compose.
postgres:
image: postgres
container_name: postgres
user: postgres
ports:
- "5432:5432"
command: 'postgres'
But agains
command: bash -c "
postgres &&
createuser -l \"auser\"
"
during the create user command, there might be the case that the DB contains is not ready to accept the connection.
So you have two best option.
POSTGRES_USER
This optional environment variable is used in conjunction with
POSTGRES_PASSWORD
to set a user and its password. This variable will create the specified user with superuser power and a database with the same name. If it is not specified, then the default user of postgres will be used.
postgres:
image: postgres
container_name: postgres
environment:
POSTGRES_USER: test
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp
user: postgres
ports:
- "5432:5432"
The second option
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
Upvotes: 10