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

  1. Choose a base image with FROM.
  2. Set a working directory with WORKDIR.
  3. Copy dependency files and install packages with COPY and RUN.
  4. Copy application source code.
  5. Define the default command with CMD or ENTRYPOINT.

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 RUN commands with && to reduce layers.
  • Use .dockerignore to exclude unnecessary files from the build context.
  • Prefer official, minimal base images like alpine or slim variants.

Common issues

  • Large image sizes caused by leaving build tools in the final image.
  • Security risks from running as root; use USER to drop privileges.
  • Build cache invalidation when copying unnecessary files early in the Dockerfile.