Search code examples
dockerdocker-entrypoint

What is the exit condition for a Docker container regarding main process and child processes?


A Docker container running a (Windows) image will exit when its entrypoint (main) process exits. However what if the main process has started other processes before its own exit? Will the container still exit even if child processes are still running, or will the container keep running until child processes exit?

I have experienced both. Can it be host OS dependent and/or Docker Desktop version dependent?


Solution

  • Quote from Docker documentation here:

    A container's main running process is the ENTRYPOINT and/or CMD at the end of the Dockerfile. It's best practice to separate areas of concern by using one service per container. That service may fork into multiple processes (for example, Apache web server starts multiple worker processes). It's ok to have multiple processes, but to get the most benefit out of Docker, avoid one container being responsible for multiple aspects of your overall application. You can connect multiple containers using user-defined networks and shared volumes.

    The container's main process is responsible for managing all processes that it starts. In some cases, the main process isn't well-designed, and doesn't handle "reaping" (stopping) child processes gracefully when the container exits. If your process falls into this category, you can use the --init option when you run the container. The --init flag inserts a tiny init-process into the container as the main process, and handles reaping of all processes when the container exits. Handling such processes this way is superior to using a full-fledged init process such as sysvinit or systemd to handle process lifecycle within your container.

    As far as I remember, each process has its own parent. If it doesn't, that means they are 'zombie' processes. It's necessary to consider what happens in your image. But I suppose when the last of children processes is closed, the main process closed and container is stopped.