Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Testing and Deployment

Docker and Deploying a Gin App

Ship a Gin service: release mode, twelve-factor configuration from environment variables, a multi-stage Dockerfile, Compose with a database, health checks and a reverse proxy.

A Gin app compiles to one static binary. That makes deployment unusually simple compared with many ecosystems: no interpreter, no dependency install on the server. This lesson walks the path from go run on your laptop to a container that runs the same way everywhere, including configuration through environment variables, a small multi-stage Dockerfile, a Compose file with a database, health checks and a reverse proxy.

Docker, Gin and GORM are not available in the in-page runner, so Dockerfiles, Compose files and Gin code are read-only. The runnable examples cover the Go parts of deployment that you can test anywhere: loading and validating configuration, and a health endpoint. If you have used Docker before, you may enjoy the dedicated Docker tutorial; it is not required here.

Production checklist for the app itself

Before packaging anything, make the program behave in production:

  1. Release mode. gin.SetMode(gin.ReleaseMode) or the environment variable GIN_MODE=release turns off debug route listings and verbose logs (see Gin Modes and Configuration).
  2. Configuration from the environment, never from files baked into the image. Secrets (database password, JWT key) must never be committed or built into an image.
  3. Explicit http.Server timeouts and graceful shutdown (next lesson).
  4. Trusted proxies configured, since you will sit behind a load balancer.
  5. Structured logs to stdout. The platform collects them; do not write log files inside a container.

Configuration from environment variables

The "twelve-factor" approach: the same build runs in development, staging and production, and only the environment differs. Read it once at startup into a struct, apply defaults and fail fast if something required is missing.

Go Load and validate configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Passing a lookup function instead of calling os.Getenv inside Load makes it trivially testable. For .env files in development, libraries like godotenv or viper load them into the environment; in production the platform sets real variables. Never print secrets in logs: the example prints only the length.

A health endpoint

Orchestrators (Docker, Kubernetes, load balancers) need to ask "is this instance alive and ready?". Provide two cheap endpoints:

  • /healthz (liveness): the process is up. Always returns 200.
  • /readyz (readiness): dependencies are reachable, for example db.PingContext. Return 503 when not ready so traffic is routed elsewhere.
Go
r.GET("/healthz", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) })
r.GET("/readyz", func(c *gin.Context) {
	ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
	defer cancel()
	if err := sqlDB.PingContext(ctx); err != nil {
		c.JSON(http.StatusServiceUnavailable, gin.H{"status": "database unavailable"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "ready"})
})
Go Readiness that follows a dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A multi-stage Dockerfile

Compile in a full Go image, then copy only the binary into a tiny runtime image. The result is often 10-20 MB with no compiler or source code in it.

DOCKERFILE
# ---- build stage ----
FROM golang:1.25 AS build
WORKDIR /src

# Copy module files first so this layer is cached until dependencies change
COPY go.mod go.sum ./
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server

# ---- runtime stage ----
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/server /server
ENV GIN_MODE=release PORT=8080
EXPOSE 8080
USER nonroot:nonroot
ENTRYPOINT ["/server"]

Points worth knowing:

  • CGO_ENABLED=0 yields a fully static binary that runs on scratch or distroless. If you use SQLite through cgo, you need a base image with libc, or a pure-Go driver.
  • Copying go.mod and go.sum before the source keeps the dependency download cached across code edits.
  • The nonroot user means a compromised app cannot do root things inside the container.
  • If you serve templates or static files, embed them with go:embed (see Static Files and Embedding Assets) so the binary is self-contained. Otherwise COPY the folders into the runtime image.
  • Add a .dockerignore with .git, .env, *.md and test data so the build context stays small and secrets stay out.

Docker Compose with a database

For local development and small deployments, Compose runs the app and its database together.

YAML
services:
  api:
    build: .
    ports: ["8080:8080"]
    environment:
      APP_ENV: production
      DATABASE_URL: "app:${DB_PASSWORD}@tcp(db:3306)/app?parseTime=true"
      JWT_SECRET: ${JWT_SECRET}
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped

  db:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: app
      MYSQL_USER: app
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_RANDOM_ROOT_PASSWORD: "yes"
    volumes:
      - dbdata:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 5s
      retries: 10

volumes:
  dbdata:

Inside the Compose network the app reaches the database by its service name (db), not localhost. The ${DB_PASSWORD} values come from a .env file next to the Compose file, which you do not commit. The named volume keeps data when the container is recreated.

Reverse proxy and TLS

Do not expose the Go server straight to the internet if you can avoid it. Put Nginx, Caddy or a cloud load balancer in front. It terminates TLS, serves static files efficiently, compresses responses, buffers slow clients and can add rate limits.

NGINX
server {
    listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate     /etc/letsencrypt/live/api.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;

    location / {
        proxy_pass         http://127.0.0.1:8080;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

Tell Gin to trust only that proxy with r.SetTrustedProxies([]string{"127.0.0.1"}), so c.ClientIP() returns the real visitor and clients cannot spoof it (see Rate Limiting and Input Safety).

flowchart LR
  U["Browser / client"] -->|HTTPS| P["Nginx or Caddy<br/>TLS, gzip, static"]
  P -->|HTTP 127.0.0.1:8080| A["Gin binary<br/>in a container"]
  A --> D[("MySQL / PostgreSQL")]

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use a multi-stage Dockerfile for a Go app?

    The build stage compiles; the runtime stage copies just the static binary.
  2. 2. Where should the database password come from?

    Secrets must stay out of source and images; the platform injects them at run time.
  3. 3. What is the difference between liveness and readiness checks?

    A live but not ready instance should be kept out of the load balancer until it recovers.
  4. 4. Inside a Compose network, how does the api container reach MySQL?

    Compose gives every service a DNS name equal to its service name.
  5. 5. What does CGO_ENABLED=0 give you?

    Without cgo the binary does not need libc, so it runs on scratch or distroless images.

Summary

  • Run in release mode, configure from environment variables, fail fast on bad configuration, and keep secrets out of images.
  • Provide liveness and readiness endpoints for orchestrators.
  • Build with a multi-stage Dockerfile and CGO_ENABLED=0; run as a non-root user in a minimal image.
  • Use Compose for app plus database, and a reverse proxy for TLS with trusted-proxy settings in Gin.

Next: Graceful Shutdown, Logging and Observability