CMD vs. ENTRYPOINT

Difficulty: Intermediate

Question

Explain the difference between CMD and ENTRYPOINT in a Dockerfile.

Answer

- **ENTRYPOINT**: Defines the main command of the image. It makes the container behave like an executable. It cannot be easily overridden during `docker run` (unless using `--entrypoint`). - **CMD**: Provides default arguments for the ENTRYPOINT. If you pass arguments to `docker run`, they completely replace the CMD values.

Code examples

Using both together

FROM alpine
ENTRYPOINT ["echo"]
CMD ["Hello World"]

If run as 'docker run my-img', it prints 'Hello World'. If run as 'docker run my-img Hi', it prints 'Hi'.

Key points

Concepts covered

Dockerfile, Startup, Default Commands