Dockerfile Cheatsheet
A Dockerfile is a text file that contains instructions for building a Docker image. It's the blueprint for an application's environment.
File Naming Convention
The Dockerfile should always be saved as Dockerfile with no file extension. Docker will automatically look for a file with this exact name when you run the docker build command.
Example Dockerfile
A simple Dockerfile for a Python web application.
# Use an official Python runtime as a parent image
FROM python:3.9-slim
# Set the working directory in the container
WORKDIR /app
# Copy the current directory contents into the container at /app
COPY . .
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 8000 available to the world outside this container
EXPOSE 8000
# Define environment variable
ENV NAME=World
# Run app.py when the container launches
CMD ["python", "app.py"]Common Dockerfile Commands
| Command | Description |
|---|---|
FROM | Specifies the base image for the build. It's usually the first instruction in a Dockerfile. |
RUN | Executes commands in a new layer on top of the current image. It's used to install packages or dependencies. |
CMD | Provides defaults for an executing container. There can only be one CMD instruction in a Dockerfile. |
ENTRYPOINT | Similar to CMD, but the command is executed as the main process of the container. Useful for containerizing executables. |
COPY | Copies files and directories from the build context to the container's filesystem. |
ADD | Similar to COPY, but can also handle tar file extraction and fetching remote URLs. COPY is generally preferred. |
WORKDIR | Sets the working directory for subsequent instructions like RUN, CMD, and COPY. |
EXPOSE | Informs Docker that the container listens on the specified network ports at runtime. |
ENV | Sets environment variables. These variables are available to subsequent instructions and the running container. |
LABEL | Adds metadata to an image, such as a maintainer or version. |