Introduction
A Dockerfile is a text file containing instructions to build a Docker image. Writing efficient Dockerfiles results in smaller images, faster builds, and better security.
Basic Dockerfile Structure
# Use a specific base image version
FROM python:3.11-slim
# Set working directory
WORKDIR /app
# Copy dependency file first (layer caching)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Expose port
EXPOSE 8000
# Run the application
CMD ["python", "app.py"]
Multi-Stage Builds
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:18-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]
Best Practices
# 1. Use .dockerignore
# .dockerignore
node_modules
.git
*.md
# 2. Minimize layers - combine RUN commands
RUN apt-get update && apt-get install -y
curl
wget
&& rm -rf /var/lib/apt/lists/*
# 3. Use non-root user
RUN useradd -m appuser
USER appuser
Summary
Write efficient Dockerfiles by using multi-stage builds, leveraging layer caching, minimizing image size, and following security best practices like using non-root users.
YouTip