← Back to docker-basics

Docker Basics: Writing Dockerfiles

Learn how to write efficient Dockerfiles for your applications

Your First Dockerfile

A Dockerfile is a text document that contains instructions for building a Docker image.

Basic Structure

# Base image
FROM golang:1.23-alpine

# Set working directory
WORKDIR /app

# Copy source code
COPY . .

# Build the application
RUN go build -o main .

# Run the application
CMD ["./main"]

Best Practices

  1. Use specific tags - Don’t use latest
  2. Multi-stage builds - Keep images small
  3. Order matters - Put frequently changing instructions last
  4. .dockerignore - Exclude unnecessary files

Multi-stage Build Example

# Build stage
FROM golang:1.23 AS builder
WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -o main .

# Runtime stage
FROM alpine:3.20
COPY --from=builder /app/main /main
CMD ["/main"]

This reduces image size significantly!