Updated Nov 20, 20265 min read

How to Write a Dockerfile for a Go App

A production Dockerfile for Go in 2026: multi-stage builds on golang:1.27, static binaries with CGO_ENABLED=0, distroless or scratch base images, build caches, cross-compiling for arm64 and graceful shutdown.

Illustration for How to Write a Dockerfile for a Go App

A good Go Dockerfile compiles in the full golang image and ships only the binary on a minimal base. Go makes this easier than most languages, since a binary built with CGO_ENABLED=0 needs nothing from the operating system beyond CA certificates.

The result is an image of a few megabytes that starts in milliseconds, and the Dockerfile below is short enough to read line by line.

What does a production Go Dockerfile look like?

# syntax=docker/dockerfile:1 FROM --platform=$BUILDPLATFORM golang:1.27 AS build WORKDIR /src # Dependencies first, so this layer is cached until go.mod or go.sum changes. COPY go.mod go.sum ./ RUN --mount=type=cache,target=/go/pkg/mod go mod download COPY . . ARG TARGETOS TARGETARCH RUN --mount=type=cache,target=/go/pkg/mod \ --mount=type=cache,target=/root/.cache/go-build \ CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \ go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server FROM gcr.io/distroless/static-debian12:nonroot COPY --from=build /out/server /server USER nonroot:nonroot EXPOSE 8080 ENTRYPOINT ["/server"]

Build it with docker build -t api:v1 ., or for both architectures with docker buildx build --platform linux/amd64,linux/arm64 -t registry.example.com/api:v1 --push .. Add a .dockerignore with .git, bin/ and local env files, so COPY . . does not invalidate the cache or leak secrets into the image.

What does each line do?

  • golang:1.27 for building only. The image is about 300 MB compressed on Docker Hub for linux/amd64, and none of it belongs in production.
  • go mod download before COPY . .. Dependencies change less often than code, so this layer stays cached across most builds.
  • BuildKit cache mounts. The Docker build cache docs describe --mount=type=cache, which keeps the module cache and compiled packages between builds, even when the layer itself is rebuilt.
  • CGO_ENABLED=0. Produces a static binary that runs on scratch or distroless static. With cgo on, the binary looks for glibc at startup and fails with exec /server: no such file or directory.
  • -trimpath -ldflags="-s -w". Removes local paths, and the linker flags drop the symbol table and DWARF debug data. On a small net/http server built with Go 1.27.3, that took the binary from 8.7 MB to 5.9 MB.
  • $BUILDPLATFORM with GOARCH=$TARGETARCH. The compiler runs natively and cross-compiles, instead of running the whole build under QEMU emulation for arm64.
  • Distroless nonroot. The distroless images include CA certificates, /etc/passwd with a nonroot user and timezone data, with no shell or package manager.

Should you use scratch or distroless?

scratch is empty, so an app that calls HTTPS APIs needs CA certificates copied in, and time.LoadLocation needs timezone data or the time/tzdata import. Distroless static has those in about 2 MB, per the distroless README, and runs as UID 65532 by default with the nonroot tag. Alpine is a third option when you want a shell for debugging, at the cost of a larger image and musl instead of glibc for cgo builds.

How should the Go server behave in a container?

Read the port from PORT, listen on all interfaces, and shut down cleanly on SIGTERM, which docker stop, Kubernetes, ECS and Cloud Run all send before killing the container:

// cmd/server/main.go package main import ( "context" "errors" "log" "net/http" "os" "os/signal" "syscall" "time" ) func main() { port := os.Getenv("PORT") if port == "" { port = "8080" } mux := http.NewServeMux() mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) }) srv := &http.Server{Addr: ":" + port, Handler: mux, ReadHeaderTimeout: 5 * time.Second} go func() { log.Printf("listening on %s", srv.Addr) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatal(err) } }() // docker stop sends SIGTERM; finish in-flight requests before exiting. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) defer stop() <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { log.Printf("shutdown: %v", err) } }

The ENTRYPOINT uses the exec form, so the binary runs as PID 1 and gets the signal directly. A shell-form ENTRYPOINT /server would run under /bin/sh, which distroless does not have, and on other bases the shell would swallow SIGTERM.

How does Encore build Go images without a Dockerfile?

Encore

Encore is a backend framework with built-in infrastructure, and it builds the container image from the application itself. encore build docker compiles the app on the host and produces an image on a scratch base for Go, and it is the same code path Encore's CI uses for deploys, per the Docker build docs. The image listens on 8080 or PORT, and --arch=arm64 targets another architecture.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

An endpoint with a database, where the Dockerfile above would also need a connection string and a migration step:

// links/links.go package links import ( "context" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("links", sqldb.DatabaseConfig{ Migrations: "./migrations", }) type CreateParams struct { Slug string URL string } type Link struct { Slug string URL string } //encore:api public method=POST path=/links func Create(ctx context.Context, p *CreateParams) (*Link, error) { _, err := db.Exec(ctx, `INSERT INTO links (slug, url) VALUES ($1, $2)`, p.Slug, p.URL) if err != nil { return nil, err } return &Link{Slug: p.Slug, URL: p.URL}, nil }
-- links/migrations/1_init.up.sql CREATE TABLE links ( slug TEXT PRIMARY KEY, url TEXT NOT NULL );
encore build docker --config=infra-config.json links-api:v1

An app with databases, Pub/Sub, object storage or secrets passes an infrastructure config file with --config, and when self-hosting the image you apply migrations yourself before starting it. On the Encore deploy path, deploying to your own AWS or GCP account builds the image, runs migrations and provisions the database there, with no Dockerfile or registry to maintain.

A coding agent working on a service like this changes Go code and the infrastructure it declares, and the image and its configuration follow from that, so there is no Dockerfile or deploy config to keep in sync with the code.

Best fit: Teams who want production images and the cloud resources behind them from the application code, without maintaining Dockerfiles per service.

What mistakes should you avoid?

  1. Shipping the golang image as the runtime image.
  2. COPY . . before go mod download, which rebuilds dependencies on every change.
  3. Leaving cgo on with a scratch or distroless static base.
  4. Shell-form ENTRYPOINT, which breaks signal handling.
  5. Running as root when the nonroot tag is one word away.
  6. Building arm64 under emulation instead of cross-compiling.

Frequently asked questions

What is the best base image for a Go app in Docker?

For a static binary built with CGO_ENABLED=0, gcr.io/distroless/static-debian12:nonroot or scratch. Distroless adds CA certificates, timezone data and a nonroot user in about 2 MB, per the [distroless README](https://github.com/GoogleContainerTools/distroless), which scratch leaves you to copy in yourself.

Why use a multi-stage Dockerfile for Go?

The [golang:1.27](https://hub.docker.com/_/golang) image is about 300 MB compressed and includes the whole toolchain. A multi-stage build compiles in that image and copies only the binary into a small runtime image, so the deployed image is a few megabytes and has no compiler or shell in it.

Do I need CGO_ENABLED=0 in a Go Dockerfile?

Yes. For distroless static or scratch, with cgo on, the binary links against the C library, which those images do not have, and it fails to start with a 'no such file or directory' error. Use a base image with glibc, such as distroless/base, if you need cgo.

How do I build a Go Docker image for arm64?

Use docker buildx build --platform linux/arm64, with the build stage on --platform=$BUILDPLATFORM and GOARCH set from TARGETARCH. Go cross-compiles natively, so the build runs at full speed without emulation.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders