From 33616baa8b0453d41b2d57c2354d17a9418a787b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20Hells=C3=A9n?= Date: Mon, 26 Feb 2024 10:09:18 +0100 Subject: [PATCH] Use scratch Docker image to minimize size --- Dockerfile | 46 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 7 deletions(-) diff --git a/Dockerfile b/Dockerfile index d437dcd..bc3704c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,12 +1,44 @@ -FROM golang:1.22-alpine +FROM golang:alpine +# Git is required for go mod download +RUN apk update && apk add --no-cache git ca-certificates + +ENV USER=anewdawn +ENV UID=10001 + +# Create anewdawn user +RUN adduser \ + --disabled-password \ + --gecos "" \ + --home "/nonexistent" \ + --shell "/sbin/nologin" \ + --no-create-home \ + --uid "${UID}" \ + "${USER}" + +# Set the working directory WORKDIR /usr/src/app -# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change -COPY go.mod go.sum ./ -RUN go mod download && go mod verify - +# Copy the current directory contents into the container at /usr/src/app COPY . . -RUN go build -v -o /usr/local/bin/app ./... -CMD ["app"] +# Download dependencies +RUN go get -d -v + +# Build the binary +RUN GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o /usr/local/bin/anewdawn + +FROM scratch + +COPY --from=0 /etc/passwd /etc/passwd +COPY --from=0 /etc/group /etc/group +COPY --from=0 /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ + +# Copy the binary from the first stage +COPY --from=0 /usr/local/bin/anewdawn /usr/local/bin/anewdawn + +# Use an unprivileged user. +USER anewdawn:anewdawn + +# Command to run the executable +ENTRYPOINT ["/usr/local/bin/anewdawn"]