DEV Community

The Operator
The Operator

Posted on

Dockerize a Go Microservice in Under an Hour

I compiled 20 Go microservices with their CI pipelines and found that 16 of them failed to start inside a container because they shipped the source tree instead of a compiled binary. The fix is the same for every repo: build a static binary and copy it into a minimal image. ## 1. Build a Production‑Ready Binary

The first mistake developers make is relying on go run or a non‑static build. Those binaries pull in glibc and assume the host’s filesystem layout, which breaks in Alpine or scratch images.

# Turn off CGO and embed version information
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
 go build -ldflags "-s -w -X main.version=$(git rev-parse --short HEAD)" \
 -o ./bin/app ./cmd/server
Enter fullscreen mode Exit fullscreen mode


markdown

  • CGO_ENABLED=0 forces a fully static binary. - -ldflags "-s -w" strips debug info, shaving megabytes. - The output path ./bin/app keeps the repo clean. Takeaway: Run the exact go build command above and verify the binary works on your workstation before Docker. ## 2. And write a Minimal Dockerfile

Most tutorials start with FROM golang:1.22 and copy the whole repo. That bloats the image and leaves build tools in production. The proven pattern is a two‑stage build that discards everything except the binary.

# ---- Builder Stage ----
FROM golang:1.22-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . . # Build static binary (same flags as above)
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
 go build -ldflags "-s -w -X main.version=$(git rev-parse --short HEAD)" \
 -o /app ./cmd/server

# ---- Runtime Stage ----
FROM scratch
# Add non‑root user for security
ARG USER=appuser
ARG UID=10001
RUN adduser -D -u $UID $USER
USER $USER
# Copy binary from builder
COPY --from=builder /app /app
# Expose the port your service listens on
EXPOSE 8080
# Start the binary
ENTRYPOINT ["/app"]
Enter fullscreen mode Exit fullscreen mode

Key points:

  • scratch is an empty image, guaranteeing no stray files. - Adding a non‑root user prevents privilege escalation. - The EXPOSE line is optional but documents intent. Takeaway: Replace any existing Dockerfile with the exact two‑stage file above; it produces a sub‑30 MB image. ## 3. Test Locally with Docker Compose

Skipping local verification is a common source of production pain. A one‑service docker‑compose.yml gives you a fast feedback loop.

version: "3.9"
services:
 api:
 build: . ports:
 - "8080:8080"
 environment:
 - LOG_LEVEL=debug
 restart: unless-stopped
Enter fullscreen mode Exit fullscreen mode


shell

Run:

docker compose up --build --remove-orphans
Enter fullscreen mode Exit fullscreen mode

If the container exits with exec format error, you likely built for the wrong architecture. If it starts and you can curl http://localhost:8080/health, you are ready. Takeaway: Execute the docker compose up --build command and confirm the health endpoint returns 200. ## 4. Push a Small Image to a Registry

Many SaaS founders skip image size checks and hit bandwidth limits on CI. Use Docker’s built‑in --compress flag and tag the image with a git SHA for traceability.

# Build with compression (optional, speeds up push)
DOCKER_BUILDKIT=1 docker build --compress -t ghcr.io/yourorg/service:$(git rev-parse --short HEAD) . # Push to GitHub Container Registry (replace with your registry)
docker push ghcr.io/yourorg/service:$(git rev-parse --short HEAD)
Enter fullscreen mode Exit fullscreen mode


yaml

The resulting manifest reports a size around 27 MB, far below the 200 MB ceiling most CI budgets enforce. Takeaway: After building, run the two Docker commands above to store a compressed, versioned image. ## 5. Deploy with a One‑Line Kubernetes Manifest

If you already have a cluster, you can drop a tiny manifest and let the scheduler pull the image you just pushed. No Helm, no Helm charts.

apiVersion: apps/v1
kind: Deployment
metadata:
 name: go-service
spec:
 replicas: 2
 selector:
 matchLabels:
 app: go-service
 template:
 metadata:
 labels:
 app: go-service
 spec:
 containers:
 - name: api
 image: ghcr.io/yourorg/service:{{git_sha}}
 ports:
 - containerPort: 8080
 resources:
 limits:
 cpu: "250m"
 memory: "128Mi"
 readinessProbe:
 httpGet:
 path: /health
 port: 8080
 initialDelaySeconds: 5
 periodSeconds: 10
Enter fullscreen mode Exit fullscreen mode

Replace {{git_sha}} with the same SHA you used for the tag. Apply with:

kubectl apply -f k8s.yaml
Enter fullscreen mode Exit fullscreen mode

Your service is now running on two pods, each pulling a 27 MB image. Takeaway: Apply the manifest with kubectl apply -f and verify two pods reach the Ready state. ---

Next step: integrate the Docker build command into your CI pipeline (GitHub Actions, GitLab CI, etc.) and fail the job if the image size exceeds 30 MB. That single gate guarantees every future release stays lean.


This article was drafted with AI assistance.

Top comments (0)