I picked up a service whose deploys were slow, and spent an embarrassing amount of time looking at the cluster before I opened the Dockerfile.
A Go service called greeter works fine. It also ships as a 314 MB image,
and every deploy drags that across the network to every node that runs it.
The code is not the problem. The Dockerfile is.
What you are looking at
In /workspace:
main.go— an HTTP service with two routes,/healthand/.go.mod— no dependencies.Dockerfile— works, and is the thing you are here to fix.
Open the Dockerfile and read it before you build anything.
Why it is so big
golang:1.23 is not a runtime image. It carries the compiler, the standard
library source, git, and a full Debian userland — everything needed to build
Go. Your service needs none of that to run: once compiled, it is a single
static binary.
So the image is mostly build tooling that will never execute in production. It is also attack surface: every package in there is something to patch.
The idea
A Dockerfile can declare more than one FROM. Each one starts a stage,
and only the last stage becomes the image you ship. Earlier stages are
scratch space — you build there, then copy out just what you need.
FROM <something with a compiler> AS builder
... compile ...
FROM <something small>
COPY --from=builder <the binary> <where it goes>
The first stage can be as heavy as it likes. It is thrown away.
Your tasks
- Build the image as it stands and look at the size. Tag it
greeter:naive. Knowing the starting number is what makes the ending number mean something. - Run it and confirm it answers on port 8080.
- Rebuild it as
greeter:slim, under 10 MB, still answering.
Verify each task when you think it is done.
Hints, if the third one resists
The final image needs the binary. Ask yourself what else it genuinely needs — and be strict about the answer.
Two flags matter when compiling for a minimal base image. CGO_ENABLED=0
produces a binary with no dynamic library dependencies, which is what lets
it run somewhere that has no C library at all. -ldflags="-s -w" drops the
symbol table and debug information, which you do not need in production and
which is a surprising share of the file.
How you will know you got it
314 MB becomes roughly 8.6 MB — about thirty-six times smaller, from a change to the Dockerfile alone, with the source untouched.
That ratio is not special to Go. Any compiled language has the same shape: the tools that build the thing are not the thing.
One thing worth saying: Alpine is not the only answer, and for some
workloads it is the wrong one — its musl libc has bitten people with DNS
resolution and with anything that expects glibc. distroless and scratch
are both reasonable choices here. This is the version I settled on, not the
version you have to use.