Steve Kallestad
Steve Kallestad

Reputation: 3573

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.

Upvotes: 7

Views: 3440

Answers (3)

Bernard
Bernard

Reputation: 17261

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.

Upvotes: 3

dnephin
dnephin

Reputation: 28050

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

Upvotes: 13

BMitch
BMitch

Reputation: 263549

I don't believe docker-compose supports this use case. However, making a simple shell script would easily resolve this:

#!/bin/sh

docker run -d --name=database personal/database
docker run --rm -it --entrypoint=/usr/bin/runmytests.sh personal/webserver
docker stop database
docker rm database

Upvotes: 2

Related Questions