Search code examples
postgresqldocker-composepsql

run psql commands in docker compose


I have a docker compose file, which spins up postgres db. How can I run some psql commands after this container is started?

enter image description here

This is what I'm trying to run:

createuser postgres

createdb DB

createdb TEST_DB

psql -d DB -c "GRANT CREATE ON DATABASE "DB" TO postgres"

psql -d DB -c "CREATE EXTENSION IF NOT EXISTS "uuid-ossp""

psql -d DB -c "CREATE EXTENSION IF NOT EXISTS "pg_trgm""

psql -d TEST_DB -c "GRANT CREATE ON DATABASE "TEST_DB" TO postgres"

psql -d TEST_DB -c "CREATE EXTENSION IF NOT EXISTS "uuid-ossp""

psql -d TEST_DB -c "CREATE EXTENSION IF NOT EXISTS "pg_trgm""


Solution

  • The official postgres image supports initialization scripts, you can save your commands in .sql file in /docker-entrypoint-initdb.d and they will be executed

    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.