Skip to content

Instantly share code, notes, and snippets.

@kszarek
Created November 8, 2018 16:53
Show Gist options
  • Save kszarek/00f3cc3117a56e92956a06ffabe30169 to your computer and use it in GitHub Desktop.
Save kszarek/00f3cc3117a56e92956a06ffabe30169 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
@iTrooz
Copy link

iTrooz commented Nov 24, 2023

Some people suggest to set the shell to /bin/false: https://stackoverflow.com/a/67703976

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment