Build a minimal, secure multi-stage Dockerfile for a Go service and prepare it for container deployment.
## CONTEXT I am containerizing a Go service and want a small, secure, fast-building image plus sensible deployment defaults. I need a multi-stage Dockerfile, a minimal base image, proper caching, and runtime hardening. Assume current Go toolchain and container best practices for 2026. ## ROLE Act as a Go platform engineer who ships lean, secure containers. You know how to leverage build caching, static binaries, and distroless or scratch images, and you harden the runtime without breaking observability. ## RESPONSE GUIDELINES - Use a multi-stage build that separates compile from runtime. - Maximize Docker layer caching for fast incremental builds. - Produce the smallest safe image and explain the base choice. - Apply runtime hardening such as a non-root user. ## TASK CRITERIA ### Structure The Build Stages - Use a builder stage with the Go toolchain and module cache. - Copy go.mod and go.sum first to cache dependency downloads. - Build a static binary with appropriate flags and trimmed paths. - Copy only the binary and assets into the runtime stage. ### Choose A Minimal Runtime - Recommend distroless or scratch and explain the trade-offs. - Include CA certificates if the service makes TLS calls. - Add timezone data only if the service needs it. - Keep the final image free of shells and package managers. ### Harden The Runtime - Run as a non-root user with a fixed UID. - Set a read-only root filesystem where possible. - Drop unnecessary capabilities and avoid privileged mode. - Define a health check or document the probe endpoint. ### Configure For Deployment - Expose configuration through environment variables. - Document required env vars and sane defaults. - Set resource requests and limits guidance for the platform. - Ensure graceful shutdown on the platform termination signal. ### Optimize Build And Size - Use build cache mounts to speed dependency and build steps. - Pin base image versions for reproducibility. - Show the resulting image size and how to inspect layers. - Recommend a vulnerability scan in the pipeline. ## ASK THE USER FOR - Your service entry point and any static assets it needs. - Whether the service makes outbound TLS calls. - Your target platform such as Kubernetes, Cloud Run, or ECS. - Any compliance or base image constraints you must follow.
Or press ⌘C to copy