3

In Docker, when chaining several startup commands (CMD) in shell form, is there any advantage in using the shell's exec feature to replace it with the last command of the chain instead of just running it as a child process of the startup shell?

Here is an example:

CMD npm install && npm start

versus:

CMD npm install && exec npm start

I think in the latter example, the npm start command will replace the shell as the PID 1 process. But I do not fully understand which advantages or disadvantages this would have.

5

When you replace pid 1 with a new executable, rather than forking it as a child pid, you reduce overhead (slightly). More importantly, you get signals directly to your application instead of having them passed to the shell running as pid 1. By default, the shell running in pid 1 will ignore the SIGTERM sent by docker to gracefully stop your application. After 10 seconds of no response, docker will send a SIGKILL which will immediately terminate the shell and child processes without giving them a chance to drain network connections or finish writing to any files. This can result in things like database corruption depending on what the app is inside the container.

Even when this doesn't apply to your application (if there's no state), you can save up to 10 seconds every time you stop the container by switching to the exec syntax (assuming your application exits when it receives a SIGTERM). Therefore the exec syntax is the one I prefer for both data safety and speed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.