What is the difference between RUN, CMD and ENTRYPOINT, and when would you use CMD versus ENTRYPOINT?
RUN executes at build time and creates a layer; CMD is the default start command, which arguments to docker run replace; ENTRYPOINT is the fixed executable that always runs, with arguments appended.
| When it runs | Overridden by | |
|---|---|---|
RUN |
While the image is built (installs packages, creates folders); the result is saved in a layer | Not applicable: it is part of the image |
CMD |
When a container starts, if no command is given | Any command after the image name in docker run |
ENTRYPOINT |
When a container starts, always | Only with an explicit docker run --entrypoint … |
Use CMD for a sensible default that users may want to replace. A general-purpose image such as CMD ["/bin/bash"] starts a shell, but docker run myimage ls /codes runs ls instead.
Use ENTRYPOINT when the container is one tool and the arguments vary. With ENTRYPOINT ["ping"], docker run pinger 8.8.8.8 runs ping 8.8.8.8.
They combine well: ENTRYPOINT holds the executable and CMD the default arguments.
ENTRYPOINT ["ping", "-c", "3"]
CMD ["localhost"]
docker run pinger pings localhost; docker run pinger hslu.ch pings hslu.ch.
Prefer the JSON (exec) form ["…"]. The shell form runs the command under /bin/sh -c, so the app is not PID 1 and won't receive stop signals properly.
Go deeper:
Docker Docs: Dockerfile reference, CMD and ENTRYPOINT interaction — the table of what runs for every combination.
Docker Docs: Dockerfile reference, shell and exec form — why the JSON form matters for signals and PID 1.