乐闻世界logo
搜索文章和话题

What is the purpose of the CMD instruction in a Dockerfile?

1个答案

1
  1. Shell Form: CMD command param1 param2 In this form, the CMD instruction executes within the shell, typically using /bin/sh -c. For example, CMD echo "Hello, World!" runs echo "Hello, World!" when the container starts.

  2. Exec Form: CMD ["executable","param1","param2"] This form directly invokes the executable without passing through the shell, avoiding limitations such as variable expansion issues. For example, CMD ["python", "app.py"] executes the python app.py command directly when the container starts.

A typical example is using the CMD instruction to run a web server container. Suppose there is a Python application based on Flask; the Dockerfile might appear as follows:

dockerfile
FROM python:3.8 COPY . /app WORKDIR /app RUN pip install -r requirements.txt EXPOSE 5000 CMD ["python", "app.py"]

In this Dockerfile, CMD ["python", "app.py"] specifies the command to execute upon container startup. This ensures that the Flask application launches every time the container starts.

It is important to note that if additional parameters are provided via the docker run command line, they override the CMD instruction in the Dockerfile. This provides runtime flexibility, allowing you to modify the container's default behavior as needed.

2024年8月9日 13:53 回复

你的答案