difference between CMD and ENTRYPOINT in dockerfile
In Docker, both CMD
and ENTRYPOINT
are instructions used to specify what command should be run within a container. However, they have different purposes and behaviors, which are important to understand to use them effectively.
CMD
The CMD
instruction specifies the default command to run when the container starts. It can be overridden by passing arguments to docker run
.
Syntax:
CMD ["executable", "param1", "param2"]
or
CMD command param1 param2
Example:
CMD ["node", "main.js"]
or
CMD node main.js
ENTRYPOINT
The ENTRYPOINT
instruction specifies a command that will always run when the container starts. It does not get overridden by the arguments provided to docker run
but can be appended with additional arguments.
Syntax:
ENTRYPOINT ["executable", "param1", "param2"]
or
ENTRYPOINT command param1 param2
Example:
ENTRYPOINT ["node", "main.js"]
or
ENTRYPOINT node main.js
Combining ENTRYPOINT
and CMD
You can combine both ENTRYPOINT
and CMD
to provide a default command with arguments that can be overridden.
Example:
ENTRYPOINT ["node"]
CMD ["main.js"]
In this case, the default command node main.js
will run. If you run docker run <image> otherfile.js
, it will execute node otherfile.js
because the CMD
is overridden.
Key Differences
-
Overriding Behavior:
CMD
can be overridden by arguments provided todocker run
.ENTRYPOINT
cannot be overridden; it ensures that the specified command is always run.
-
Purpose:
- Use
CMD
when you want to provide default arguments that can be changed. - Use
ENTRYPOINT
when you want to define the main command to run, ensuring it will always be executed.
- Use
Usage Scenarios
-
CMD: Use when you need a default command that the user might want to change.
FROM node:14 WORKDIR /app COPY . . CMD ["node", "main.js"]
-
ENTRYPOINT: Use when your container must always run a specific application.
FROM node:14 WORKDIR /app COPY . . ENTRYPOINT ["node", "main.js"]
-
Combining Both: Use when you need a default behavior but also want to allow flexibility.
FROM node:14 WORKDIR /app COPY . . ENTRYPOINT ["node"] CMD ["main.js"]