Skip to content

Instantly share code, notes, and snippets.

@developer-guy
Forked from kszarek/Dockerfile
Created March 4, 2021 19:44
Show Gist options
  • Save developer-guy/f1cbe412c3782c535a90609c8bee629d to your computer and use it in GitHub Desktop.
Save developer-guy/f1cbe412c3782c535a90609c8bee629d to your computer and use it in GitHub Desktop.
Go application on docker scratch image
# 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