In Docker, CMD and ENTRYPOINT are Dockerfile instructions that can both be used to specify the command executed when the container starts. However, there are key differences between them, primarily in how they handle commands and arguments, and how they influence the container's execution behavior.
1. Default Behavior
- CMD: The
CMDinstruction provides the default command for the container. If no command is specified at startup, the command and arguments defined inCMDare executed. If a command is specified during startup, theCMDcommand is overridden. - ENTRYPOINT: The
ENTRYPOINTinstruction sets the command executed when the container starts, making the container run centered around a specific program or service. UnlikeCMD, even if other commands are specified during startup, theENTRYPOINTcommand is still executed, and the startup command is passed as arguments to theENTRYPOINT.
2. Usage Scenarios
- Using CMD:
In this case, if no command is specified at startup, it executesdockerfileFROM python:3.8 COPY script.py /script.py CMD ["python", "/script.py"]python /script.py. If a command is specified, such asdocker run <image> bash, theCMDcommand is overridden withbash. - Using ENTRYPOINT:
In this case, regardless of whether a command is specified at startup, thedockerfileFROM python:3.8 COPY script.py /script.py ENTRYPOINT ["python", "/script.py"]ENTRYPOINTis executed, and the startup command is passed as arguments topython /script.py. For example, if you rundocker run <image> arg1 arg2, the actual command executed ispython /script.py arg1 arg2.
3. Combined Usage
CMD and ENTRYPOINT can be used together, where the content of CMD is passed as arguments to the ENTRYPOINT. For example:
dockerfileFROM python:3.8 COPY script.py /script.py ENTRYPOINT ["python"] CMD ["/script.py"]
In this example, if no startup command is specified, the container executes python /script.py by default. If arguments are specified, such as arg1, the command becomes python /script.py arg1.
By understanding and combining these, you can more flexibly control the startup behavior and argument handling of Docker containers.
2024年8月10日 00:22 回复