Goglides Dev 🌱

Balkrishna Pandey
Balkrishna Pandey

Posted on

How to use CMD and ENTRYPOINT in your Dockerfiles (Difference)

The main difference between ENTRYPOINT and CMD is that ENTRYPOINT defines the executable that will be run when the container starts, while CMD defines the default arguments that will be passed to that executable.

In other words, if you specify an ENTRYPOINT in your Dockerfile, you are specifying the command that will be run when your container starts. The CMD instruction, on the other hand, is used to specify default arguments for that ENTRYPOINT command.

If you don't specify an ENTRYPOINT in your Dockerfile, then the default ENTRYPOINT will be used, which is /bin/sh -c . This means that the command specified in the CMD instruction will be executed as /bin/sh -c <cmd> .

Take a look at the following simple Dockerfile,

FROM busybox
LABEL maintainer "Balkrishna Pandey"
RUN wget -c "https://dl.k8s.io/release/$(wget -qO-  https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
RUN mv ./kubectl /kubectl && chmod +x /kubectl
USER 1001
ENTRYPOINT [ "/kubectl" ]
CMD [ "--help" ]
Enter fullscreen mode Exit fullscreen mode

In the above file we have defined that our application is kubectl command (CMD) with --help argument (ENTRYPOINT). Now we can override these default values while running the container.

First, build the container as follows,

docker build -t kubectl-test .
Enter fullscreen mode Exit fullscreen mode

Now we can override default values as follows,

docker run --rm -it kubectl-test version
Enter fullscreen mode Exit fullscreen mode

The output of the above command will be,

WARNING: This version information is deprecated and will be replaced with the output from kubectl version --short. Use --output=yaml|json to get the full version.

Client Version: version.Info{Major:"1", Minor:"24", GitVersion:"v1.24.3", GitCommit:"aef86a93758dc3cb2c658dd9657ab4ad4afc21cb", GitTreeState:"clean", BuildDate:"2022-07-13T14:30:46Z", GoVersion:"go1.18.3", Compiler:"gc", Platform:"linux/amd64"}

Kustomize Version: v4.5.4

The connection to the server localhost:8080 was refused - did you specify the right host or port?
Enter fullscreen mode Exit fullscreen mode

Top comments (0)