Using this docker file you will reduce your golang docker image from ~1GB to ~40MB and you will rebuild your image faster
# Stage 1: Build the Go application
FROM golang:1.23-alpine AS builder
# Set the working directory inside the container
WORKDIR /app
# Copy the Go module files
COPY go.mod go.sum ./
# Download Go module dependencies
RUN go mod download
# Copy the rest of the application code
COPY . .
# Build the Go application
RUN go build -o main cmd/server/main.go
# Stage 2: Minimal image for running the app
FROM alpine:latest as runner
# Set environment variables (optional)
ENV GO_ENV=production
# Create a directory for the application
WORKDIR /app
# Copy the binary from the builder stage
COPY --from=builder /app/main .
# Expose the port on which the application runs (if applicable)
EXPOSE 8080
# Command to run the application
CMD ["./main"]
Top comments (2)
There's also another way to do it for those who don't want to deal with multi-stage builds :-) DockerSlim (aka MinToolkit, aka SlimToolkit) will recreate your image from "scratch" and it'll copy everything you need including the Go binary and any dependencies it might have (e.g., user info, timezone info, certs, etc).
Basic usage info: mint slim your-golang-app-container-image
Lots of examples here (for Go apps and not only :-)): github.com/mintoolkit/examples
A couple of Go examples:
github.com/mintoolkit/examples/tre...
github.com/mintoolkit/examples/tre...
Very nice, thanks for sharing!