The things I've collected to write my best Dockerfile. Appreciate any comments mentioning I could do it better and more optimal.
Preface
TLDR:
FROM golang:1.23.1-alpine AS builder
WORKDIR /app
ENV CGO_ENABLED=0
ENV GOOS=linux
COPY go.mod go.mod
COPY go.sum go.sum
RUN go mod download -x
COPY . .
FROM builder AS dev
RUN go install github.com/go-delve/delve/cmd/dlv@v1.23.0
RUN go build -gcflags=all="-N -l" -o server ./cmd/server
CMD ["dlv", "--listen=:40000", "--continue", "--headless=true", "--api-version=2", "--accept-multiclient", "exec", "server"]
FROM builder AS prod
RUN go build -ldflags "-s -w" -o server ./cmd/server
FROM alpine:3.13
RUN addgroup -g 1001 appgroup && adduser -D -G appgroup -u 1001 appuser
WORKDIR /app
USER 1001
COPY /app/server server
CMD ["/app/server"]
Link: https://github.com/treenq/treenq/blob/98e6d8dd5f5756fe5df561913e10515784ef7163/Dockerfile
Now let's breakdown what's happening here and why.
note
I use colima and all the things described here work well. However, all the docs referenses will go to docker. I think they did a great job to push the industry standart. Also you have to turn on buildx to make these features work. It requires buildx installation and setting a feature flag DOCKER_BUILDKIT=1
.