The CMD instruction in a Dockerfile provides defaults for executing a container, specifying the command to run when no command is provided at container startup.
The CMD instruction defines the default command to execute when a container starts from the image. It serves as the primary process that keeps the container alive. Unlike RUN, which executes during image build, CMD executes at container runtime. If no command is specified when running the container (with docker run), CMD provides the defaults. Users can override CMD by specifying a command after the image name in docker run.
CMD has three forms. The exec form (CMD ["executable", "param1", "param2"]) is the preferred format, running the command directly without shell processing. The shell form (CMD command param1 param2) invokes /bin/sh -c, which provides shell features like variable substitution but may cause signal handling issues. The parameter form (CMD ["param1", "param2"]) is used exclusively with ENTRYPOINT to provide default arguments. There can only be one CMD instruction in a Dockerfile, and if multiple appear, only the last one takes effect.
CMD is executed at container runtime, not during image build—distinct from RUN which builds layers .
The command specified by CMD becomes PID 1 in the container and should run in the foreground to keep the container alive .
CMD can be easily overridden by providing a command after the image name when running the container .
When used with ENTRYPOINT, CMD provides default arguments that can be overridden at runtime .
Only one CMD instruction is effective—if multiple are present, the last one wins .