skip to Main Content

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""

2

Answers


  1. Chosen as BEST ANSWER

    postgres image initialization scripts did it! I used COPY in my Dockerfile to copy some .sh files to the container.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search