Gin in the wider system · 6 MIN READ
Shipping a Gin binary: release mode, a /version endpoint from build info, static builds and a non-root image
Build a Gin service for production with release mode, -trimpath, -ldflags -X and CGO_ENABLED=0, report its identity from runtime/debug build info, and package it in a minimal non-root image.
The binary you test with go run is not the one you ship. A release build differs in Gin's mode, in what the toolchain stamps into the executable, in how it links and in the image around it. Each difference has a failure attached: request headers in debug logs, an incident where nobody can say which commit is running, a container that will not start because a C library is missing. This lesson follows the build from the mode switch to the final image.
gin · A MAP OF THE IDEA
- Fix the Gin mode owner
- Stamp version and VCS
- Build static, trimmed
- Run non-root, no secrets
Useful when
- /version answers which commit is running in one request.
- A static binary on distroless has a tiny attack surface and no shell.
Watch out
- An unknown GIN_MODE panics in Gin init, before main.
- With -trimpath the -ldflags value is absent from build info.
- ARG and ENV values are readable in the image history.
Implementation & operation cost: A few build flags and a two-stage Dockerfile; you give up a shell in the runtime image, so debugging moves to logs, the admin listener and ephemeral debug containers.
What Gin's debug mode does in production
Gin reads GIN_MODE once, in its package init, and an empty value means debug, or test under go test. Debug mode prints the route table and warnings to stdout, re-parses templates loaded with LoadHTMLGlob on every render, and when Recovery catches a panic it logs the request's headers with only Authorization masked, so cookies and API-key headers reach the logs. Release mode drops all of that. An unknown value is not ignored: GIN_MODE=production makes SetMode panic inside Gin's init, before main runs and before your logger exists. Pick one owner for the mode. Either the deployment sets GIN_MODE=release and nothing calls SetMode, or validated configuration calls gin.SetMode before any engine is built, as the config-startup lesson does, and GIN_MODE stays unset. Two owners eventually disagree.
Report the build identity at /version
debug.ReadBuildInfo returns the running binary's own record, which differs on every build, so the program parses a fixed record in the same text format with debug.ParseBuildInfo. It also validates a mode setting, shows what SetMode does with an unknown value, and serves /version twice: as go run links it, and with a version string as -ldflags -X would set it.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"runtime/debug"
"github.com/gin-gonic/gin"
)
// version is set at link time: go build -ldflags "-X main.version=v1.4.0".
var version = ""
// A fixed build record in the format debug.BuildInfo.String produces.
// In the service, debug.ReadBuildInfo returns the running binary's own record.
const recorded = "go\tgo1.27.3\n" +
"path\texample.com/notes-api/cmd/api\n" +
"mod\texample.com/notes-api\tv1.4.0\t\n" +
"dep\tgithub.com/gin-gonic/gin\tv1.12.0\th1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=\n" +
"build\t-buildmode=exe\n" +
"build\t-compiler=gc\n" +
"build\t-trimpath=true\n" +
"build\tCGO_ENABLED=0\n" +
"build\tGOARCH=amd64\n" +
"build\tGOOS=linux\n" +
"build\tGOAMD64=v1\n" +
"build\tvcs=git\n" +
"build\tvcs.revision=9f3c2b7d41e0a5c8b6f1e2d3c4b5a69788796a5b\n" +
"build\tvcs.time=2026-11-17T09:30:00Z\n" +
"build\tvcs.modified=false\n"
type Version struct {
Version string `json:"version"`
Revision string `json:"revision"`
Time string `json:"time"`
Modified bool `json:"modified"`
Go string `json:"go"`
Gin string `json:"gin"`
Cgo bool `json:"cgo"`
}
func versionFrom(bi *debug.BuildInfo, linked string) Version {
v := Version{Version: linked, Go: bi.GoVersion}
if v.Version == "" {
v.Version = bi.Main.Version // "(devel)" when the build had no VCS or tag data
}
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
v.Revision = s.Value
case "vcs.time":
v.Time = s.Value
case "vcs.modified":
v.Modified = s.Value == "true"
case "CGO_ENABLED":
v.Cgo = s.Value == "1"
}
}
for _, d := range bi.Deps {
if d.Path == "github.com/gin-gonic/gin" {
v.Gin = d.Version
}
}
return v
}
// ginMode validates the mode from the service's own config and defaults to
// release, where Gin itself would default to debug.
func ginMode(configured string) (string, error) {
switch configured {
case "":
return gin.ReleaseMode, nil
case gin.ReleaseMode, gin.DebugMode, gin.TestMode:
return configured, nil
}
return "", fmt.Errorf("mode %q: want release, debug or test", configured)
}
func newRouter(v Version) *gin.Engine {
r := gin.New()
r.Use(gin.Recovery())
r.GET("/version", func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusOK, v)
})
return r
}
func main() {
for _, configured := range []string{"", "debug", "production"} {
mode, err := ginMode(configured)
fmt.Printf("config %q -> mode %q, err %v\n", configured, mode, err)
}
func() {
defer func() { fmt.Println("gin.SetMode(\"production\") panics:", recover()) }()
gin.SetMode("production")
}()
gin.SetMode(gin.ReleaseMode) // no route table or debug warnings on stdout
fmt.Println("mode", gin.Mode(), "debugging", gin.IsDebugging())
bi, err := debug.ParseBuildInfo(recorded)
if err != nil {
panic(err)
}
fmt.Printf("parsed GoVersion %q: ParseBuildInfo skips the go line\n", bi.GoVersion)
bi.GoVersion = "go1.27.3" // ReadBuildInfo fills this from runtime.Version()
for _, linked := range []string{version, "v1.4.0-rc.2"} {
w := httptest.NewRecorder()
newRouter(versionFrom(bi, linked)).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/version", nil))
fmt.Println(w.Code, w.Body.String())
}
}ginMode accepts the three names Gin knows and maps an empty setting to release, the opposite of Gin's own default. SetMode panics on anything else, and recover turns that into a printed line here. ParseBuildInfo reads the path, mod, dep and build lines but skips the go line, because ReadBuildInfo fills GoVersion from runtime.Version() separately, so the program sets it by hand. versionFrom prefers the linked string, falls back to the main module version, which go build derives from a VCS tag or reports as (devel), and copies vcs.revision, vcs.time and vcs.modified. Cache-Control: no-store stops caches from reporting a previous deploy's identity.
Build flags that make the binary honest
-trimpath removes the build machine's directories from file names recorded in the binary, so stack traces do not reveal home directories and builds from different checkouts match. -ldflags "-X main.version=..." sets a package-level string variable at link time; for other packages it needs the full import path, it works only on a variable that is uninitialized or initialized to a constant string, and a misspelled name is silently ignored, which is why /version should be checked after every build. -s -w drop the symbol table and DWARF data: panics and pprof still name functions because they use the runtime's own tables, but a debugger has less to work with. CGO_ENABLED=0 matters because the golang image has a C compiler, so cgo is on by default and net and os/user link against the system C library.
VERSION=$(git describe --tags --always --dirty)
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -trimpath -ldflags "-s -w -X main.version=${VERSION}" -o bin/api ./cmd/api
go version -m bin/api | grep -E 'vcs\.|CGO_ENABLED|trimpath'
file bin/apiRun these in your own checkout. git describe prints a tag-based version with a -dirty suffix when the tree has uncommitted changes. go version -m prints the record the /version handler reads; expect vcs.revision, vcs.time, vcs.modified, CGO_ENABLED=0 and -trimpath=true. One surprise: with -trimpath, go build leaves -ldflags out of that record, because linker flags can contain local paths, so the -X value is visible only through the variable it set. file should report a statically linked executable.
A multi-stage image with a distroless, non-root runtime
The containers lesson builds a basic two-stage image on scratch. For a Gin API, the distroless static image is a better default runtime: it adds CA certificates for outbound TLS, time zone data, an /etc/passwd with a nonroot user and a /tmp directory, and still has no shell or package manager. A cgo-linked binary fails in it with a confusing no such file or directory, because the missing file is the dynamic loader, not your program. Use a numeric USER: when a Pod sets runAsNonRoot without a runAsUser, Kubernetes can verify only a numeric image user and refuses to start a container whose image names one. If .dockerignore excludes .git, as it usually should, go build has no VCS data inside the build, the vcs fields are empty and the version is (devel), so CI passes the version in as a build argument.
# syntax=docker/dockerfile:1
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
ARG VERSION=dev
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux go build -trimpath \
-ldflags "-s -w -X main.version=${VERSION}" -o /out/api ./cmd/api
# Pin the digest you reviewed: static-debian12:nonroot@sha256:...
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/api"]This Dockerfile runs in your own environment: docker build --build-arg VERSION=$(git describe --tags --always --dirty) -t notes-api:dev . The build stage holds the toolchain, module cache and source; only /out/api crosses into the runtime stage. Cache mounts keep downloads and compiled packages between builds without storing them in any layer. The exec-form ENTRYPOINT makes the binary PID 1, so it receives SIGTERM directly, which the rolling-deploys lesson relies on.
What must not be baked into the image
Anything in a layer or in the image config is readable by everyone who can pull the image, forever. ARG and ENV values are recorded in the image history, so a token passed as a build argument is published; private module credentials belong in a BuildKit secret mount used by a single RUN step and never written to a layer. Environment-specific settings, such as database URLs, tokens, trusted proxy ranges or a debug mode, come from the orchestrator at runtime, so the same digest can be promoted from staging to production as the delivery lesson requires. The source tree, .git, .env files, fixtures and local binaries stay out through .dockerignore. Decide what /version itself may reveal: version, revision, commit time and the modified flag help operators, while hostnames, environment values or the full dependency list help attackers. A production response with modified true is itself a finding: someone shipped uncommitted code.
TAKE THIS WITH YOU
Ship with release mode set by one owner, -trimpath, CGO_ENABLED=0 and a -X version; report vcs.revision, vcs.time and vcs.modified from build info at /version, and run as a numeric non-root user with no secrets in any layer.
Check your understanding
A Gin binary built in the golang image runs on the build host but fails in a distroless static container with "no such file or directory". What is the likely cause?
Go to the source
Progress stays in this browser. No account needed.