I need to start backend-container after start database-container. How can I do it with docker-compose?

asked May 2, 2019 at 20:51

Andrey Kadnikov's user avatar

Use a depends_on clause on your backend-container. Something like that :

version: "3.7"
services:
  web:
    build: .
    depends_on:
      - db
  db:
    image: postgres

Here is the documentation about it. Have fun!

answered May 2, 2019 at 20:57

Schisme's user avatar

SchismeSchisme

4632 silver badges6 bronze badges

You should look into the depends_on configuration for docker compose.

In short, you should be able to do something like:

services:
  database-container:
    # configuration
  backend-container:
    depends_on:
      - database-container
    # configuration

answered May 2, 2019 at 20:57

Erik Tate's user avatar

The depends_on field will work with docker-compose, but you will find it is not supported if you upgrade to swarm mode. It also guarantees the database container is created, but not necessarily ready to receive connections.

For that, there are several options:

  • Let the backend container fail and configure a restart policy. This is ugly, leads to false errors being reported, but it's also the easiest to implement.
  • Perform a connection from your app with a retry loop, a sleep between retries, and a timeout in case the database doesn't start in a timely fashion. This is usually my preferred method, but it requires a change to your application.
  • Use an entrypoint script with a command like wait-for-it.sh that waits for a remote resource to become available, and once that command succeeds, launch your app. This doesn't cover all the scenarios as a complete client connection, but can be less intrusive to implement since it only requires changes to an entrypoint script rather than the app itself.

answered May 3, 2019 at 3:04

BMitch's user avatar

BMitchBMitch

265k50 gold badges542 silver badges499 bronze badges

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.