1

I have a docker compose file with an app container and a postgres container.

The app one depends on postgres container.

I would like before the app container starts to connect to the postgres and run a script to create a database there. How can I do this in docker compose? Is there any way to run something in the middle of the dependency?

Or should I do it when I connect to the server through ssh, to run docker compose up and down, in the deploy stage. In this way I would also need to somehow install psql in the server. I would prefer the first one.

Can you point me in the right direction?

1
  • Does one of the answers help you out? If so, please accept it and close the question. Otherwise, we will try to help you further. Commented Sep 13, 2019 at 6:17

2 Answers 2

2

I would like before the app container starts to connect to the postgres and run a script to create a database there.

You can achieve something like this by mounting (SQL) scripts into the Postgres container's /docker-entrypoint-initdb.d folder (see the image documentation – Initialization Scripts). With this, your app does not have to connect to the PostgreSQL container, but the container does it all on its own.

A common problem here, though, is that your app might immediately try to connect to PostgreSQL before it is ready to accept connections and your app crashes. You can avoid this by either implementing some try-catch mechanism in your app to wait for PostgreSQL to be ready, or you change the entrypoint of your app container, i.e. sleep 10 && [run_your_app].

Sign up to request clarification or add additional context in comments.

Comments

1

By declaring the environment variable POSTGRES_DB you can tell Postgres to create an empty database at startup and use the env vars name.

version: '3.5'

services:

  db:
    image: postgres:11.2-alpine
    restart: always
    environment:
      POSTGRES_DB: myDB
      POSTGRES_PASSWORD: myPassword
      POSTGRES_USER: myUser

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.