Skip to content

Instantly share code, notes, and snippets.

@ChristianWitts
Created November 9, 2018 06:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChristianWitts/8568a446b13cb43714b38c2496daf5b2 to your computer and use it in GitHub Desktop.
Save ChristianWitts/8568a446b13cb43714b38c2496daf5b2 to your computer and use it in GitHub Desktop.
Golang Scratch Builder
# This is the first stage, for building things that will be required by the
# final stage (notably the binary)
FROM golang
# Copy in just the go.mod and go.sum files, and download the dependencies. By
# doing this before copying in the other dependencies, the Docker build cache
# can skip these steps so long as neither of these two files change.
COPY go.mod go.sum ./
RUN go mod download
# Assuming the source code is collocated to this Dockerfile
COPY . .
# Build the Go app with CGO_ENABLED=0 so we use the pure-Go implementations for
# things like DNS resolution (so we don't build a binary that depends on system
# libraries)
RUN CGO_ENABLED=0 go build -o /myapp
# Create a "nobody" non-root user for the next image by crafting an /etc/passwd
# file that the next image can copy in. This is necessary since the next image
# is based on scratch, which doesn't have adduser, cat, echo, or even sh.
RUN echo "nobody:x:65534:65534:Nobody:/:" > /etc_passwd
# The second and final stage
FROM scratch
# Copy the binary from the builder stage
COPY --from=0 /myapp /myapp
# Copy the certs from the builder stage
COPY --from=0 /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
# Copy the /etc_passwd file we created in the builder stage into /etc/passwd in
# the target stage. This creates a new non-root user as a security best
# practice.
COPY --from=0 /etc_passwd /etc/passwd
# Run as the new non-root by default
USER nobody
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment