CMD and ENTRYPOINT are two instructions that you can use in a Dockerfile to define what commands or processes will run when you start a container from an image. They have some differences and similarities that you need to understand.
- CMD defines the default command or parameters that will run when you start a container. You can use CMD to provide a default argument for an executable defined by ENTRYPOINT, or to run a standalone command. You can also override CMD by providing a different command or argument when you run the container. For example, if you have a Dockerfile with CMD ["echo", "Hello World"], you can override it by running docker run myimage echo Goodbye World. CMD is useful when you want to provide a default behavior for your container that can be easily changed by the user.
- ENTRYPOINT defines the specific executable that will run when you start a container. You cannot override ENTRYPOINT unless you use the --entrypoint flag when you run the container. For example, if you have a Dockerfile with ENTRYPOINT ["ping"], you cannot override it by running docker run myimage echo Hello World. You have to use docker run --entrypoint echo myimage Hello World. ENTRYPOINT is useful when you want to define a container as an executable that always runs the same command or process.
- You can also combine CMD and ENTRYPOINT to define a container with a specific executable and a default parameter that can be modified easily. For example, if you have a Dockerfile with ENTRYPOINT ["ping"] and CMD ["google.com"], you can run the container as docker run myimage and it will ping google.com by default. But you can also change the parameter by running docker run myimage yahoo.com and it will ping yahoo.com instead. This way, you can use the same image for different purposes without changing the executable.