How to write a Dockerfile?
· Category: Docker
Short answer
A Dockerfile is a text document containing instructions to assemble a Docker image. Key instructions include FROM, WORKDIR, COPY, RUN, and CMD, each defining a step in the image creation process.
Steps
- Choose a base image with
FROM. - Set a working directory with
WORKDIR. - Copy dependency files and install packages with
COPYandRUN. - Copy application source code.
- Define the default command with
CMDorENTRYPOINT.
Example Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Build the image:
docker build -t mydjango .
Tips
- Order instructions from least to most frequently changing to maximize layer caching.
- Combine related
RUNcommands with&&to reduce layers. - Use
.dockerignoreto exclude unnecessary files from the build context. - Prefer official, minimal base images like
alpineorslimvariants.
Common issues
- Large image sizes caused by leaving build tools in the final image.
- Security risks from running as root; use
USERto drop privileges. - Build cache invalidation when copying unnecessary files early in the Dockerfile.