HiveBrain v1.2.0
Get Started
← Back to all entries
principledockerMinor

In Docker, is there any advantage or disadvantage in using 'CMD cmd1 && cmd2' versus 'CMD cmd1 && exec cmd2'?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
cmd1cmd2versusdockeranydisadvantagecmdusingexecthere

Problem

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.

Solution

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.

Context

StackExchange DevOps Q#6051, answer score: 6

Revisions (0)

No revisions yet.