Home > front end >  How to make a docker container exit with a specific error-code with docker-compose?
How to make a docker container exit with a specific error-code with docker-compose?

Time:03-01

I can spin up a Docker container with docker-compose and check its exit code with this example:

# Dockerfile
FROM alpine:3.15 as base
# docker-compose.yml
version: '3.6'
services:
  dummy:
    build:
      context: .
    entrypoint: ["sleep", "42"]
    image: "tmp:tmp"
$ docker-compose up --force-recreate
WARNING: The Docker Engine you're using is running in swarm mode.

Compose does not use swarm mode to deploy services to multiple nodes in a swarm. All containers will be scheduled on the current node.

To deploy your application across the swarm, use `docker stack deploy`.

Recreating docker-compose_dummy_1 ... done
Attaching to docker-compose_dummy_1
docker-compose_dummy_1 exited with code 0
$ docker inspect docker-compose_dummy_1 --format='{{.State.ExitCode}}' # 42 seconds later
0

Is there a way I can have this container exit with a specific error code?
I'd like the result of my docker inspect to return a nonzero value specifiable in my docker-compose.yml.

I naively thought changing the entrypoint from sleep to exit should work:

# docker-compose.yml
version: '3.6'
services:
  dummy:
    build:
      context: .
    entrypoint: ["exit", "42"]
    image: "tmp:tmp"

...but it did not:

$ docker-compose up --force-recreate
WARNING: The Docker Engine you're using is running in swarm mode.

Compose does not use swarm mode to deploy services to multiple nodes in a swarm. All containers will be scheduled on the current node.

To deploy your application across the swarm, use `docker stack deploy`.

Recreating docker-compose_dummy_1 ... error

ERROR: for docker-compose_dummy_1  Cannot start service dummy: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"exit\": executable file not found in $PATH": unknown

ERROR: for dummy  Cannot start service dummy: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"exit\": executable file not found in $PATH": unknown
ERROR: Encountered errors while bringing up the project.

CodePudding user response:

Look at your error messages more closely:

ERROR: for docker-compose_dummy_1  Cannot start service dummy: OCI
runtime create failed: container_linux.go:345: starting container
process caused "exec: \"exit\": executable file not found in $PATH":
unknown

When you specify an entrypoint like ["exit", "42"], it's not executed in a shell. Docker is looking for a command in your $PATH named exit, and of course no such command exists.

You need to run your commands in a shell, because exit is a shell command:

    entrypoint: ["/bin/sh", "-c", "exit 42"]
  • Related