Building Images
Writing Dockerfiles
Create Dockerfiles to build custom images for your applications.
Dockerfile Instructions
A Dockerfile is a text file with instructions to build an image. Key instructions:
FROM— base image to build onWORKDIR— set working directoryCOPY— copy files from host to imageRUN— execute commands during buildENV— set environment variablesEXPOSE— document which port the app usesCMD— default command when container startsENTRYPOINT— configure container as executable
Best Practices
- Use official base images
- Order instructions from least to most frequently changed (for caching)
- Use multi-stage builds to keep images small
- Don't run as root
- Use
.dockerignoreto exclude unnecessary files
Example
bash
# Dockerfile for a Node.js app
FROM node:20-alpine AS base
WORKDIR /app
# Copy package files first (separate layer for caching)
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy source code
COPY . .
# Set environment
ENV NODE_ENV=production
ENV PORT=3000
# Expose the port
EXPOSE 3000
# Non-root user for security
RUN addgroup -g 1001 -S nodejs && adduser -S nextjs -u 1001
USER nextjs
# Start the app
CMD ["node", "server.js"]
# Multi-stage build (smaller production image)
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS production
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production
CMD ["node", "dist/server.js"]
# Build the image
# docker build -t my-app:1.0 .
# docker build -t my-app:latest -f Dockerfile.prod .Try it yourself — BASH