Multi-stage Dockerfiles for Go
You can separate Go compilation from the distroless runtime so the API and worker images contain only their executables.
Learning outcomes
- Explain how multi-stage builds separate Go compilation from the production runtime.
- Organize Docker layers so dependency downloads remain cached when application source changes.
- Build static Go binaries for distroless runtime images that execute as non-root users.
- Configure Compose services with restart policies, healthchecks, and persistent named volumes.
- Keep credentials outside Docker image layers using environment interpolation and an uncommitted
.envfile.
The Go API and worker currently run alongside development tools, source code, and a Go compiler. Shipping that entire environment to a production server increases image size and leaves tools available that the running applications do not need. You need two small application images and a production Compose configuration that connects them to MySQL, Redis, and Redpanda.
Build and runtime stages
A single-stage Dockerfile puts compilation and execution in the same image.
For example, consider this Dockerfile for the API:
FROM golang:1.27
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o /api ./cmd/api
ENTRYPOINT ["/api"]This builds the API, but the resulting image still contains the Go compiler, module cache, and development tools. None of them is required to execute /api.
A production image should contain the executable and its runtime requirements, not the environment that created it.
Separate compilation from execution
A multi-stage build uses multiple FROM instructions in one Dockerfile. Each instruction starts a new build stage with its own filesystem.
The build stage handles dependencies and compilation. The runtime stage receives the compiled executable.
For the API, the build stage starts with:
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod downloadThe golang:1.27 image provides the compiler and Go development tools. The name build identifies this stage for later COPY --from instructions.
After downloading dependencies, the build stage copies the source and compiles the API.
COPY . .
RUN CGO_ENABLED=0 go build -o /api ./cmd/apiThe output is an executable named /api. The worker uses the same structure but compiles ./cmd/worker into /worker.
The important distinction is that both executables are produced in the build stage. They do not need to carry the build environment into production.
Docker layer caching
The order of Dockerfile instructions affects build time.
Docker caches the result of an instruction when its inputs and preceding layers have not changed. You can take advantage of this by copying the Go module manifests before the application source.
The module manifests are go.mod and go.sum.
go.moddescribes the module and its dependency requirements.go.sumrecords checksums used to verify downloaded module content.go mod downloaddownloads the dependencies specified by the module.
These files describe your Go module dependencies.
Consider what happens when you modify a handler in internal/restaurant but leave the dependencies unchanged.
With the dependency manifests copied separately, Docker can reuse the dependency-download layer. It only needs to copy the changed application source and rebuild the executable.
If you copy all source files before downloading dependencies, ordinary application changes can invalidate the download layer.
This optimization matters when CI builds images after every code change. Reusing the dependency layer avoids repeating downloads that have already been completed.
Build context
Docker can only access files inside the build context.
For this project, the build context is backend/. Dockerfile paths such as go.mod, go.sum, and cmd/api are therefore relative to that directory.
You can build the API image from the repository root:
docker build \
-f backend/Dockerfile.api \
-t zomato-api:local \
backend/The -f argument identifies the Dockerfile. The final argument identifies the build context.
This distinction also matters when you configure Compose. The API and worker build configurations must use the backend directory as their context.
Excluding unnecessary files
The build context can contain files that should never enter a production image.
For example, .env may contain database credentials or signing secrets. Git metadata is also unnecessary for compiling the application.
A .dockerignore file excludes these files before Docker sends the build context to its builder.
For this project, the important exclusions are:
.env
.gitKeep backend/.dockerignore beside the Dockerfiles.
Excluding .env prevents the real local configuration from entering the build context. Excluding .git avoids sending repository history and metadata to the builder.
A .dockerignore file is not a replacement for safe Dockerfile design. You should still avoid copying unnecessary files into the runtime stage.
Static Go binaries and distroless images
A production Go executable should not depend on libraries that its runtime image does not contain.
The CGO_ENABLED=0 setting disables CGO during compilation. CGO allows Go programs to call C code through a C toolchain.
For example:
RUN CGO_ENABLED=0 go build -o /api ./cmd/apiThis builds the API without enabling CGO.
For dependencies that support pure Go operation, this produces a static Go binary suitable for a static distroless runtime.
Dynamic linking and runtime dependencies
A dynamically linked executable can depend on shared libraries installed on the operating system.
On Linux, it can also depend on a dynamic loader that loads those libraries when the process starts.
Consider an executable that requires the system C library.
Its runtime environment needs both the executable and the libraries it expects to find. If the runtime image does not provide them, the executable may fail to start.
You might see:
no such file or directoryThis error can occur even when the executable exists at the expected path. The missing file may actually be the dynamic loader requested by the executable.
The gcr.io/distroless/static image is intended for statically linked applications. It does not provide a conventional system environment with arbitrary shared libraries and development utilities.
Disabling CGO avoids this dependency for applications whose dependencies have pure Go implementations. It does not guarantee that every third-party library supports compilation without CGO.
Check your dependency requirements and test the resulting executable inside the actual runtime image.
Distroless runtime images
A distroless image contains only the runtime components needed by the application.
It does not include a conventional shell, package manager, or general-purpose development environment.
For the API, the runtime stage can begin like this:
FROM gcr.io/distroless/static:nonroot
WORKDIR /
COPY --from=build /api /apiThe COPY --from=build instruction copies the executable from the build stage.
It does not copy the Go source tree, compiler, module cache, or other development tools.
The static:nonroot image is a suitable base for the statically linked application. It also provides a non-root runtime identity.
The worker uses the same approach, copying its own executable into its runtime image.
The final image is considerably smaller than the original Go build image because it does not contain the development environment.
This is also why you should keep the build and runtime stages separate rather than trying to remove development tools from the original image afterward.
Non-root process execution
A container commonly starts as the root user unless its image or configuration specifies another identity.
Root privileges are unnecessary for the API and worker. The API needs to serve HTTP and gRPC requests, while the worker processes background events and communicates with Kafka-compatible infrastructure.
Neither process needs unrestricted administrative privileges.
A Dockerfile can explicitly select the runtime identity:
USER nonroot:nonroot
ENTRYPOINT ["/api"]The USER instruction tells Docker to execute the application under the specified user and group.
A non-root container limits the privileges available to the application process. This reduces the potential damage if an attacker compromises the application.
It does not prevent every form of exploitation. It is one layer of container security.
Exec-form entrypoints
The application should start directly as the container's main process.
Docker supports two forms of ENTRYPOINT.
Shell form:
ENTRYPOINT /apiExec form:
ENTRYPOINT ["/api"]The exec form starts the executable directly instead of invoking it through a shell.
This matters for signal handling. Docker sends termination signals to the container's main process. When the application runs directly as that process, it can receive and handle those signals.
The shell form can introduce an intermediate shell process, which complicates signal forwarding and shutdown behaviour.
There is another reason to use exec form here: distroless images do not contain a shell. An entrypoint that depends on /bin/sh cannot work in this runtime.
Distroless debugging
Removing the shell makes interactive debugging different.
For example:
docker exec -it zomato-api shThis fails because the container does not contain sh.
That is expected. Installing debugging utilities into the production image would defeat part of the purpose of using distroless.
You can still investigate a running container through Docker.
Read application logs:
docker logs zomato-apiInspect container configuration and state:
docker inspect zomato-apiInspect its processes:
docker top zomato-apiMonitor resource consumption:
docker stats zomato-apiInspect its exit status and restart count:
docker inspect --format \
'{{.State.Status}} {{.State.ExitCode}} {{.RestartCount}}' \
zomato-apiFor interactive debugging, use a separate development image containing diagnostic tools. Keep those tools out of the production runtime image.
Production service topology
Two application images are not enough to run the complete backend.
The API and worker depend on infrastructure that must also run in the deployment environment.
Docker Compose lets you describe multiple containers and their configuration in one compose file.
For this project, compose.prod.yml describes six services:
| Service | Responsibility |
|---|---|
mysql | Stores accounts, restaurants, menus, and orders. |
redis | Provides caching and shared temporary state. |
redpanda | Provides Kafka-compatible event streaming. |
api | Runs the Go HTTP API and the outbox relay. |
worker | Runs the notifier that consumes order events. |
caddy | Provides the reverse proxy for the application. |
Each service has its own image and lifecycle.
The API and worker also have separate application images:
ghcr.io/yashdagar/zomato-api
ghcr.io/yashdagar/zomato-workerTheir Compose configurations can describe both the image name and the local build configuration.
This allows you to build the images locally while retaining the image names used by deployment.
Service names as network addresses
Compose creates a network for the services in a project.
Containers on that network can resolve other services by their Compose service names.
For example, the API needs these internal connection settings:
REDIS_ADDR: redis:6379
KAFKA_BROKERS: redpanda:9092Its MySQL connection must also use mysql as the hostname.
This is different from connecting to localhost.
Inside the API container, localhost refers to the API container itself. It does not refer to the MySQL, Redis, or Redpanda containers.
Using service names allows the application to communicate with the correct infrastructure services without hardcoding container IP addresses.
Restart policies and readiness
A container can stop unexpectedly because of a process failure or another runtime problem.
A Compose restart policy controls how Docker handles stopped containers.
For example:
restart: unless-stoppedThis policy allows Docker to restart the container after an unexpected exit and after a Docker daemon restart, unless the container was explicitly stopped.
Apply the policy consistently to the production services.
However, restarting a container is not the same as checking whether its dependencies are ready.
MySQL healthchecks
MySQL needs time to initialize its data directory and begin accepting connections.
If the API starts before MySQL is ready, its initial database connection may fail.
A MySQL healthcheck gives Docker a way to determine when the database is ready.
For example:
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1"]
interval: 5s
timeout: 3s
retries: 20
start_period: 20sThe healthcheck runs a command inside the MySQL container. Docker uses its result to track the service's health status.
The command must use utilities available in the selected MySQL image. A healthcheck that runs an unavailable command cannot establish meaningful readiness.
Dependency conditions
Compose supports dependency conditions that control startup ordering.
For the API and worker, use:
depends_on:
mysql:
condition: service_healthyThe API and worker wait for MySQL's healthcheck to report a healthy status before Compose starts them.
This is more meaningful than a dependency that only waits for the MySQL container to start.
There is an important distinction:
restartcontrols what happens when a container stops.healthcheckdetermines whether a container passes its configured health test.service_healthycontrols when a dependent service can start.
These mechanisms solve different problems.
A service can also become unhealthy after the API has started. The startup dependency does not guarantee permanent database availability.
Your Go application must continue to handle connection errors, request timeouts, and temporary infrastructure failures.
Persistent state with named volumes
Containers are replaceable. You should not rely on a container's writable filesystem to preserve database data.
MySQL stores its data under:
/var/lib/mysqlRedpanda stores its data under:
/var/lib/redpanda/dataA named volume gives Docker-managed storage that exists independently of an individual container.
For example, declare volumes at the top level:
volumes:
mysql_data:
redpanda_data:Then mount each volume into its corresponding service:
services:
mysql:
volumes:
- mysql_data:/var/lib/mysql
redpanda:
volumes:
- redpanda_data:/var/lib/redpanda/dataWhen Docker recreates either container, the service can use the existing volume instead of starting with an empty data directory.
The distinction between removing containers and removing volumes matters.
This command stops the services and removes their containers and network:
docker compose -f compose.prod.yml downNamed volumes are preserved by default.
This command also removes the project's named volumes:
docker compose -f compose.prod.yml down -vUse the second command carefully. Removing a database volume removes its persistent data.
Redis can also use persistent storage when the application requires it. The decision depends on which Redis data must survive a restart.
Environment configuration and secrets
The same application image may run in development, staging, and production.
Its database credentials and other configuration values should come from the environment rather than being embedded into the image.
A Compose environment file provides values for Compose variable interpolation.
For this project, the example configuration includes:
MYSQL_ROOT_PASSWORD=local-root-password
JWT_SECRET=local-development-jwt-secret
API_DOMAIN=localhost
API_TAG=local
WORKER_TAG=localThese values belong in the tracked backend/.env.example file. They are examples, not production credentials.
The actual .env file contains local configuration values. Compose can read it for interpolation when evaluating the compose file.
For example, the MySQL service can obtain its root password through:
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}The API and worker can also receive interpolated configuration.
environment:
MYSQL_DSN: root:${MYSQL_ROOT_PASSWORD}@tcp(mysql:3306)/zomato?parseTime=true
JWT_SECRET: ${JWT_SECRET}Notice that the Dockerfile does not contain these credentials.
This separation matters because Docker image configuration and build layers can expose values included during image construction.
Avoid placing credentials in Dockerfile ARG or ENV declarations. Do not copy the real .env into the image.
Tracking the example file
The repository's root .gitignore already excludes .env.
Keep that rule intact.
Be careful with broad ignore patterns such as .env*. Such a pattern can also exclude .env.example, which is supposed to remain tracked.
The example file documents the configuration expected by the compose file. Every variable referenced through ${VAR} should have a corresponding entry in .env.example, including the application image tag variables.
For a real production deployment, a protected secrets-management mechanism is preferable to committing example credentials or treating a local .env file as a secure secrets store.
From images to the production stack
You now have the mental model behind the production container configuration.
The build stage compiles the API and worker. The runtime stage receives their executables without the Go development environment. Static binaries make the applications suitable for the static distroless runtime, while explicit non-root execution limits their privileges.
The compose file connects those images to MySQL, Redis, Redpanda, and Caddy. Restart policies control container recovery, healthchecks establish dependency readiness, and named volumes preserve database and broker state.
The next exercise, Production container stack, brings these pieces together.
Pay particular attention to the boundaries between the files:
backend/Dockerfile.apibuilds the API.backend/Dockerfile.workerbuilds the worker.backend/.dockerignorecontrols the build context.backend/.env.exampledocuments required configuration.backend/compose.prod.ymldescribes the production services and their relationships.
You should be able to explain why each file exists and what failure it prevents before putting the deployment together.
Check your understanding
You change a handler in internal/restaurant but do not modify go.mod or go.sum. Which Dockerfile arrangement allows Docker to reuse the dependency-download layer?
References
Everything above is explained on this page; these are where it comes from (Docker, Go).