What happens if you add more than one CMD instruction to a Dockerfile?
What happens if you add more than one CMD instruction to a Dockerfile?
In a Dockerfile, if you add more than one CMD
instruction, only the last CMD
instruction will be executed when the container starts. This is because Docker will override any previous CMD
instructions with the last one specified in the Dockerfile.
Here’s a detailed explanation:
Single Execution: Docker is designed to execute only one CMD
instruction. If multiple CMD
instructions are present, Docker will ignore all but the last one. This means that the final CMD
instruction in the Dockerfile will be the one that gets executed when the container starts[1][3][5].
Overriding Behavior: The CMD
instruction sets default parameters that can be overridden from the Docker Command Line Interface (CLI) when a container is run. However, this overriding behavior applies only to the last CMD
instruction specified in the Dockerfile[1][5].
Best Practices: It is a best practice to have only one CMD
instruction in a Dockerfile to avoid confusion and ensure predictable behavior. If you need to run multiple commands, you can use a shell script or combine commands using shell operators like &&
or ;
within a single CMD
instruction[7][10].
Consider the following Dockerfile:
FROM ubuntu:latest
CMD ["echo", "Hello World"]
CMD ["echo", "Goodbye World"]
In this example, when the container starts, it will only execute the second CMD
instruction:
echo "Goodbye World"
The first CMD
instruction (echo "Hello World"
) will be ignored.
If you need to run multiple commands, you can combine them in a single CMD
instruction using shell syntax:
FROM ubuntu:latest
CMD ["sh", "-c", "echo Hello World && echo Goodbye World"]
In this case, both commands wi...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào