Victor Bocharsky
Victor Bocharsky

Reputation: 12306

How to start Docker container only after another container is exited

Let's suppose I have 2 containers: composer and php, which share the same code base, i.e. the same volume. And I want to manage them with a single docker-compose command like docker-compose up.

So the question is How can I start these containers one by one, not at the same time? I mean, start my php container only after composer one is exited, i.e. composer container should install all vendors for my php container and exit, then and only then php container should start a built-in PHP web server with already installed vendors.

P.S. Now I get the behavior that both containers start at the same time. So my php container is trying to start web server without vendors, while composer container is trying to install these vendors.

Is there a good solution for this case?

Upvotes: 8

Views: 12027

Answers (2)

Marco Bresson
Marco Bresson

Reputation: 152

Since 2023, you have have a new option for the condition of depends_on called service_completed_successfully, and it works exactly as you would expect (see documentation).

For instance, if you want to run database migrations in a separate container (which you should do to avoid concurrency issues, and migrations that try to run multiple times), you would have the following docker compose file:

compose.yaml:

services:
  migrations:
    build: .
    command: ./run_migrations.sh
    depends_on:
      db:
        condition: service_healthy
        restart: true
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
        restart: true
      migrations:
        condition: service_completed_successfully
  db:
    image: postgres
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      retries: 5
      start_period: 30s
      timeout: 10s

Upvotes: 1

İsmail Atkurt
İsmail Atkurt

Reputation: 1390

There are couple of things can help you;

  • depends_on: it does not wait for another service to finish, it only waits until the other services starts. see: depends_on
  • health_check: it does not start the service until the command returns success. see: healthcheck
  • create a shell script to order of initialisation of your containers/services. see: startup order

Upvotes: 6

Related Questions