Docker – Check is container/service running with docker-compose

dockerdocker-compose

I am using the docker-compose.

Some commands like up -d service_name or start service_name are returning right away and this is pretty useful if you don't want the containers running to depend on the state of the shell, like they do with regular up service_name. The one use-case is running it from some kind of continious integration/delivery server.

But this way of running/starting services does not provide any feedback about the actual state of the service afterwards.

The Docker Compose CLI reference for up command does mention the relevant option, but, as for version 1.7.1, it is mutually exclusive with -d:

--abort-on-container-exit  Stops all containers if any container was stopped.
                           *Incompatible with -d.*

Can I somehow manually check that the container is indeed working and haven't stopped because of some error?

Best Answer

  • docker-compose ps -q <service_name> will display the container ID no matter it's running or not, as long as it was created.
  • docker ps shows only those that are actually running.

Let's combine these two commands:

if [ -z `docker ps -q --no-trunc | grep $(docker-compose ps -q <service_name>)` ]; then
  echo "No, it's not running."
else
  echo "Yes, it's running."
fi

docker ps shows short version of IDs by default, so we need to specify --no-trunc flag.

UPDATE: It threw "grep usage" warning if the service was not running. Thanks to @Dzhuneyt, here's the updated answer.

if [ -z `docker-compose ps -q <service_name>` ] || [ -z `docker ps -q --no-trunc | grep $(docker-compose ps -q <service_name>)` ]; then
  echo "No, it's not running."
else
  echo "Yes, it's running."
fi