Câu hỏi phỏng vấn Docker
Câu hỏi

What happens if you add more than one CMD instruction to a Dockerfile?

Câu trả lời

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:

  1. 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].

  2. 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].

  3. 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].

Example

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.

Combining Commands

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

middle

Gợi ý câu hỏi phỏng vấn

middle

Explain when to use Docker vs Docker Compose vs Docker Swarm vs Kubernetes

middle

What is the difference between Kubernetes and Docker?

junior

What is Docker container?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào