How to Write a Dockerfile: A Beginner’s Guide

A Dockerfile is a text file that contains instructions for building a Docker image. Writing a clean, efficient Dockerfile is essential for creating reproducible, lightweight containers. Below are the core steps and best practices.

Start with a base image that fits your application’s needs (e.g., python:3.11-slim or node:18-alpine). Then add your code, install dependencies, and define how the container should run. Each line in a Dockerfile creates a new layer, so order and minimalism matter.

Article illustration

1. Choose a Base Image Wisely

Use official images from Docker Hub. Prefer slim or Alpine variants to reduce image size. For example:

  • FROM node:18-alpine – small Node.js image
  • FROM python:3.12-slim – Python without bloat

2. Set the Working Directory and Copy Files

Use WORKDIR to define the container’s working directory. Then copy your application files using COPY:

WORKDIR /app
COPY package*.json ./
COPY . .

Copying package.json separately before the rest leverages Docker’s layer caching.

3. Install Dependencies and Run Commands

Use RUN to execute commands during build. Combine multiple commands into one RUN to reduce layers:

RUN npm install && npm cache clean --force

For Python: RUN pip install --no-cache-dir -r requirements.txt

4. Expose Ports and Define the Entrypoint

Use EXPOSE to document which port the container listens on (does not publish it). Use CMD or ENTRYPOINT to set the default command:

EXPOSE 3000
CMD ["npm", "start"]

Tip: Prefer the exec form (array) over shell form for cleaner signal handling.

Writing a Dockerfile is straightforward once you break it down: start with a base, copy code, install deps, and set the runtime command. Optimize with caching and minimal layers to keep your images fast and secure.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *