Gist: Multi-stage Go container build
Build your Go container properly with multi-stage builds.
Last updated on: 2025-01-07
Building the container image
Here's a sample Containerfile for building the container image:
# Build executable using official Go image. # Doc: https://hub.docker.com/_/golang FROM golang:1.23.4 as build WORKDIR /build # Pre-copy / cache "go.mod" file for pre-downloading dependencies # and only redownloading them in subsequent builds if they change. COPY go.mod go.sum ./ RUN go mod download && go mod verify # Copy source code and build executable. COPY . . RUN GOOS=linux CGO_ENABLED=0 go build -o main # Run executable using official Linux Alpine image. # Doc: https://hub.docker.com/_/alpine/ FROM alpine:3.21.1 WORKDIR / COPY --from=build /build/main . EXPOSE 8080 ENTRYPOINT [ "./main" ]
Build the image:
podman build -f containerfile -t myapp .
Running the image
To start the container, simply run:
podman run -it --rm myapp
Notes
Please note that:
- We're using Podman here but you can use any other OCI-compatible alternative.
- This is only boilerplate code to get you started.
- Consider using a non-root user for security.