🐳 Docker Beginner

What is the difference between CMD and ENTRYPOINT in Dockerfile?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Docker development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

Both define what runs when a container starts, but they work differently: CMD provides the default command and arguments to run. It can be completely overridden by providing a command after the image name in docker run: docker run myimage /bin/bash overrides CMD. Three forms: shell form: CMD npm start; exec form (preferred): CMD ["node", "app.js"]; list form (args for ENTRYPOINT). ENTRYPOINT sets the main executable — it is NOT overridden by docker run command arguments; those arguments are appended to ENTRYPOINT instead. Override ENTRYPOINT only with docker run --entrypoint. Two forms: shell form: ENTRYPOINT npm (runs in shell, signals not forwarded properly); exec form (preferred): ENTRYPOINT ["node"]. Together: use ENTRYPOINT for the main executable and CMD for default arguments: ENTRYPOINT ["node"]; CMD ["app.js"] — runs node app.js by default; docker run myimage server.js runs node server.js (CMD overridden but ENTRYPOINT preserved). Best practices: use exec form (JSON array syntax) for both to ensure signals (SIGTERM for graceful shutdown) are sent directly to the process, not to a shell wrapper.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Docker codebase.