-
Shell Form:
CMD command param1 param2In this form, theCMDinstruction executes within the shell, typically using/bin/sh -c. For example,CMD echo "Hello, World!"runsecho "Hello, World!"when the container starts. -
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 thepython app.pycommand 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:
dockerfileFROM 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.