Pulling images from Docker Hub is easy. Building your own images is where Docker becomes powerful. A Dockerfile defines exactly how your application runs in a container. Write it well, and your images are small, secure, and fast. Write it poorly, and you get 2GB images with security vulnerabilities. In this lesson, you'll learn to write production-grade Dockerfiles.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Write optimized Dockerfiles for any application
- Use multi-stage builds to reduce image size
- Understand Dockerfile instructions (FROM, RUN, COPY, CMD, ENTRYPOINT)
- Implement layer caching for faster builds
- Follow Docker security best practices
- Reduce image size from GB to MB
2. Why This Matters
Real-world scenario: Your CI/CD pipeline builds images that take 10 minutes and are 1.5GB each. With an optimized Dockerfile, you can reduce build time to 2 minutes and image size to 150MB. Faster deploys, less bandwidth, and more secure containers.
3. Core Concepts
Dockerfile Instructions
# FROM - Base image (always first)
FROM ubuntu:22.04
FROM python:3.11-slim
FROM node:20-alpine
# WORKDIR - Set working directory
WORKDIR /app
# COPY - Copy files from host to image
COPY . /app
COPY --chown=appuser:appuser . /app
COPY --from=builder /app/dist /app/dist
# ADD - Like COPY but with URL and tar support
ADD https://example.com/file.tar.gz /tmp/
ADD app.tar.gz /app/
# RUN - Execute commands during build
RUN apt-get update && apt-get install -y curl
RUN pip install -r requirements.txt
# ENV - Set environment variables
ENV NODE_ENV=production
ENV PORT=8080
# ARG - Build-time variables
ARG VERSION=1.0.0
ENV APP_VERSION=$VERSION
# EXPOSE - Document which ports are used (doesn't publish)
EXPOSE 8080
EXPOSE 3000/tcp
# USER - Switch to non-root user
RUN useradd -m appuser
USER appuser
# VOLUME - Create mount point for persistent data
VOLUME ["/data"]
# HEALTHCHECK - Check if container is healthy
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# CMD - Default command (can be overridden)
CMD ["node", "server.js"]
# ENTRYPOINT - Fixed command (cannot be overridden)
ENTRYPOINT ["python", "app.py"]
Essential Dockerfile instructions
Base Image Selection
# ❌ BAD: Large, unnecessary tools
FROM ubuntu:22.04 # ~77MB
FROM node:18 # ~990MB
FROM python:3.11 # ~900MB
# ✅ GOOD: Slim variants
FROM ubuntu:22.04 # Still 77MB, but can be smaller
FROM node:18-slim # ~180MB
FROM python:3.11-slim # ~120MB
# ✅ BEST: Alpine (musl libc, very small)
FROM node:20-alpine # ~130MB
FROM python:3.11-alpine # ~50MB
FROM alpine:3.19 # ~7MB
# ✅ DISTROLESS (most secure, no shell)
FROM gcr.io/distroless/static-debian11
FROM gcr.io/distroless/python3
# ✅ Specific versions (never use :latest)
FROM node:20.11.0-alpine # Good
FROM node:latest # Bad - unpredictable
Base image selection
Layer Caching Optimization
# ❌ BAD: Changes invalidate all subsequent layers
FROM python:3.11-slim
COPY . /app # Changes every build!
RUN pip install -r /app/requirements.txt # Re-runs every build
# ✅ GOOD: Order layers from least to most frequently changing
FROM python:3.11-slim
# 1. Install system dependencies (rarely change)
RUN apt-get update && apt-get install -y \
gcc \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*
# 2. Install Python dependencies (change only when requirements changes)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 3. Copy application code (changes most frequently)
COPY . .
# 4. Set runtime configuration
ENV PYTHONUNBUFFERED=1
CMD ["python", "app.py"]
Optimizing layer caching
Multi-Stage Builds
# Multi-stage builds: build in one stage, copy only artifacts to final
# Stage 1: Build (has all build tools)
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o myapp .
# Stage 2: Runtime (no build tools, tiny image)
FROM alpine:3.19
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/myapp .
CMD ["./myapp"]
# Result: 1.2GB builder image → 12MB final image
# Python example
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "app.py"]
Multi-stage builds for tiny images
Node.js Production Dockerfile
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files
COPY package*.json ./
COPY yarn.lock ./
# Install dependencies
RUN npm ci --only=production
# Copy source and build
COPY . .
RUN npm run build
# Stage 2: Production
FROM node:20-alpine
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
adduser -S nodejs -u 1001
WORKDIR /app
# Copy from builder
COPY --from=builder --chown=nodejs:nodejs /app/node_modules ./node_modules
COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=builder --chown=nodejs:nodejs /app/package.json ./
# Security: drop capabilities
USER nodejs
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"
CMD ["node", "dist/server.js"]
Production Node.js Dockerfile
Python Production Dockerfile
# Stage 1: Builder
FROM python:3.11-slim AS builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
libpq-dev \
&& rm -rf /var/lib/apt/lists/*
# Install Python dependencies
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt
# Stage 2: Runtime
FROM python:3.11-slim
# Create non-root user
RUN groupadd -r appuser && useradd -r -g appuser appuser
WORKDIR /app
# Copy dependencies from builder
COPY --from=builder --chown=appuser:appuser /root/.local /home/appuser/.local
# Copy application
COPY --chown=appuser:appuser . .
# Set PATH
ENV PATH=/home/appuser/.local/bin:$PATH
ENV PYTHONUNBUFFERED=1
# Switch to non-root user
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:8000", "--workers", "4"]
Production Python Dockerfile
4. Complete Project: Multi-Container App Dockerfiles
# docker-compose.yml with optimized Dockerfiles
version: '3.8'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
target: production # Use production stage
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://postgres:password@db:5432/app
- REDIS_URL=redis://redis:6379
depends_on:
- db
- redis
restart: unless-stopped
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:3000"
depends_on:
- backend
db:
image: postgres:15-alpine
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
- POSTGRES_DB=app
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
redis:
image: redis:7-alpine
command: redis-server --appendonly yes
volumes:
- redis_data:/data
restart: unless-stopped
volumes:
postgres_data:
redis_data:
Complete multi-container setup with optimized Dockerfiles
5. Common Errors & Solutions
6. Summary Checklist
7. Next Steps
Next lesson: Docker Lesson 5.3: Docker Compose
Comments (0)
This is exactly what I needed! The initContainer approach solved our migration issues completely. Thanks for the detailed guide!
ReplyLeave a Comment