Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one close a dependent container with docker-compose?

I have two containers that are spun up using docker-compose:

web:
  image: personal/webserver
  depends_on:
    - database
  entrypoint: /usr/bin/runmytests.sh
database:
  image: personal/database

In this example, runmytests.sh is a script that runs for a few seconds, then returns with either a zero or non-zero exit code.

When I run this setup with docker-compose, web_1 runs the script and exits. database_1 remains open, because the process running the database is still running.

I'd like to trigger a graceful exit on database_1 when web_1's tasks have been completed.

like image 618
Steve Kallestad Avatar asked Sep 26 '16 10:09

Steve Kallestad


Video Answer


2 Answers

You can pass the --abort-on-container-exit flag to docker-compose up to have the other containers stop when one exits.

like image 100
dnephin Avatar answered Nov 08 '22 09:11

dnephin


What you're describing is called a Pod in Kubernetes or a Task in AWS. It's a grouping of containers that form a unit. Docker doesn't have that notion currently (Swarm mode has "tasks" which come close but they only support one container per task at this point).

There is a hacky workaround beside scripting it as @BMitch described. You could mount the Docker daemon socket from the host. Eg:

web:
  image: personal/webserver
  depends_on:
    - database
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  entrypoint: /usr/bin/runmytests.sh

and add the Docker client to your personal/webserver image. That would allow your runmytests.sh script to use the Docker CLI to shut down the database first. Eg: docker kill database.

Edit: Third option. If you want to stop all containers when one fails, you can use the --abort-on-container-exit option to docker-compose as @dnephin mentions in another answer.

like image 40
Bernard Avatar answered Nov 08 '22 08:11

Bernard