For a long time, I can not tell the exact difference between CMD
and ENTRYPOINT
in Dockerfile.
Until I have a chance to take a look for the definition.
I will explain this base on few different scenarios.
Let's say If I have a Ubuntu image-based container named ubuntu-sleeper to execute the sleep
for 5 seconds. And the Dockerfile showed as below.
FROM ubuntu
CMD sleep 5
When I type docker run ubuntu-sleeper
, container will automatically execute the sleep 5
to sleep 5 seconds.
But what if I like to customize the second to sleep?
As we know, we can overwrite the default CMD by appending the command after the docker run
.
For example, docker run ubuntu-sleeper sleep 10
But it looks bad, and we like make it look like this.
docker run ubuntu-sleeper 10
Which only pass the second argument we need.
To achieve this, we can use ENTRYPOINT, to write our dockerfile..
FROM ubuntu
ENTRYPOINT ["sleep"]
Docker will execute the command in ENTRYPOINT first, then the CMD.
So, when we type docker run ubuntu-sleeper 10
.
Docker will get the ENTRYPOINT sleep
and the 10
we passed via run commmad.
But what if I run this container without passing the CMD?
For example, just run docker run ubuntu-sleeper
.
As we know, this will make container only run sleep
without given argument. And you will get the error says the operand is missing.
So how do you define the default value for this container?
In this case, You can define ENTRYPOINT and CMD at a same time.
FROM ubuntu
ENTRYPOINT ["sleep"]
CMD ["5"]
So when you simply run docker run ubuntu-sleeper
, the container will sleep 5 seconds by default.
And you can change CMD
value by docker run ubutnu-sleeper 20
PS: And you can even change the ENTRYPOINT with --entrypoint
option in docker run
.
docker run --entrypoint sleep2.0 ubuntu-sleeper 10
Top comments (1)
Nice article, thanks a lot 👌