Practical Examples and Use Cases
To better understand the practical applications of CMD
and ENTRYPOINT
, let's explore a few real-world examples:
Example 1: Running a Simple Web Server
Imagine you want to create a Docker image that runs a simple web server using Python's built-in http.server
module. Here's how you can use CMD
and ENTRYPOINT
to achieve this:
## Dockerfile using CMD
FROM python:3.9-slim
WORKDIR /app
COPY . /app
CMD ["python", "-m", "http.server", "8000"]
In this example, the CMD
instruction sets the default command to run the Python web server on port 8000.
## Dockerfile using ENTRYPOINT
FROM python:3.9-slim
WORKDIR /app
COPY . /app
ENTRYPOINT ["python", "-m", "http.server"]
CMD ["8000"]
In this version, the ENTRYPOINT
instruction sets the executable to the Python web server, and the CMD
instruction sets the default port to 8000. This allows you to easily override the port by passing a different argument to the docker run
command.
Example 2: Running a Database Migration Script
Another common use case is running database migration scripts as part of the container startup process. Here's an example using ENTRYPOINT
:
FROM python:3.9-slim
WORKDIR /app
COPY . /app
ENTRYPOINT ["python", "migrate.py"]
In this example, the ENTRYPOINT
instruction sets the executable to the migrate.py
script, which can perform any necessary database migrations when the container is started.
You can also use ENTRYPOINT
to wrap a command-line tool and add additional functionality or behavior. For instance, you might want to create a Docker image that runs the git
command-line tool with some custom configuration or additional features.
FROM alpine:latest
RUN apk add --no-cache git
ENTRYPOINT ["git"]
CMD ["--help"]
In this example, the ENTRYPOINT
instruction sets the executable to the git
command, and the CMD
instruction sets the default argument to display the Git help menu. This allows you to run the container and execute any Git command by passing arguments to the docker run
command.
These examples demonstrate how CMD
and ENTRYPOINT
can be used to create flexible and customizable Docker containers for a variety of use cases.