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
- Use specific tags - Don’t use
latest - Multi-stage builds - Keep images small
- Order matters - Put frequently changing instructions last
- .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!