DevOps

Go (Golang) Dockerfile Generator

Scaffold a production-optimized Dockerfile for Go applications with Go module caching, multi-stage builds, and ultra-minimal scratch or Alpine runtime images.

Options

# Stage 1: Builder
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o main .

# Stage 2: Runner
FROM alpine:3.18
WORKDIR /app
COPY --from=builder /app/main .
ENV NODE_ENV=production
EXPOSE 3000
RUN adduser -D appuser
USER appuser
CMD ["./main"]

Go (Golang) Dockerfile Generator: Complete Guide

Ultra-Minimal Go Docker Images with Scratch

Go is uniquely suited for Docker because it compiles to a self-contained binary. By setting CGO_ENABLED=0 and using 'scratch' as the final image, you can produce production images under 15MB with zero attack surface — no shell, no package manager, no OS.

# Stage 1: Builder
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /app/main .

# Stage 2: Runner
FROM alpine:3.18
WORKDIR /app
COPY --from=builder /app/main .
EXPOSE 8080
CMD ["./main"]

How to Use

  1. 1

    Runtime Pre-Selected

    This page has pre-configured the generator for Go (Golang). Adjust port, base image, and environment variables as needed.

  2. 2

    Toggle Multi-Stage Build

    Enable multi-stage builds to separate the build environment from the runtime, drastically reducing image size.

  3. 3

    Enable Non-Root Security

    Check the non-root user option to run your container as a non-privileged user for production security.

  4. 4

    Copy & Use

    Switch between Dockerfile, docker-compose.yml, and .dockerignore tabs to copy each file.

Frequently Asked Questions

How do I Dockerize a Go application?+

Go compiles to a single static binary. Use a multi-stage Dockerfile: the builder stage compiles with 'CGO_ENABLED=0 go build', and the runner stage copies only the binary into a scratch or Alpine image. Final images can be as small as 10-20MB.

What is a scratch Docker image and why use it for Go?+

scratch is an empty Docker image with zero files. Since Go binaries are statically compiled (when CGO_ENABLED=0), they don't need a Linux distribution, libc, or any other runtime. This produces the smallest and most secure Docker images possible.