Home  Tech   Difference ...

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

  1. Overriding Behavior:

    • CMD can be overridden by arguments provided to docker run.
    • ENTRYPOINT cannot be overridden; it ensures that the specified command is always run.
  2. 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.

Usage Scenarios

Published on: Jun 14, 2024, 03:08 AM  
 

Comments

Add your comment