CMD, ENTRYPOINT and PID 1

How to set the start command so that signals reach the program.

The start command is set by two instructions. CMD is the default command: anything you write after the image name in docker run replaces it. ENTRYPOINT is the fixed part of the command: arguments from docker run are appended to it. Together they work like this: ENTRYPOINT is the program and CMD its default arguments.

ENTRYPOINT ["python", "report.py"]
CMD ["--format", "text"]
docker run report-image
docker run report-image --format json

The first run executes python report.py --format text, the second python report.py --format json: the command-line arguments replaced only CMD.

Both instructions have two forms. The exec form is a JSON array, as in the example above: the program is started directly and becomes process number 1. The shell form is a string such as CMD python app.py: Docker starts /bin/sh -c, so the shell becomes number 1 and your program is its child process.

Number 1 matters. It is process 1 that receives SIGTERM from docker stop. In the shell form the shell usually does not pass the signal on, the program never sees it, and after 10 seconds the container is killed with SIGKILL. That is why CMD and ENTRYPOINT use the exec form. If a preparation script has to run before the start, it ends with the line exec "$@" so that the program replaces the shell and becomes process 1.

A common mistake is mixing the forms: an ENTRYPOINT in shell form ignores CMD and the docker run arguments, and the flags simply never reach the program. If arguments “vanish”, check that both instructions are written as JSON arrays with double quotes. Docker does not understand single quotes in the array and silently runs the string through the shell.

Practice

  1. Where the arguments go

    The image has ENTRYPOINT ["python", "report.py"] and CMD ["--format", "text"]. What runs with docker run image --format json?

    • python report.py --format text
    • python report.py --format json
    • --format json without python
    • python report.py --format text --format json
  2. The shell form

    What is true for CMD python app.py written as a string? Mark all.

    • /bin/sh becomes process 1
    • The program receives SIGTERM from docker stop right away
    • Stopping may drag on until SIGKILL
    • This is the exec form
  3. The main process

    What process number (PID) does a program started with the exec form of CMD have inside the container? Answer with a number.