feat(docker): optimize Dockerfile for multi-stage builds

- Introduced a builder stage to separate build dependencies.
- Added a dev stage for runtime dependencies and live reload tools.
- Reduced image size by cleaning up unnecessary files in the builder
stage.
- Improved build efficiency by copying only necessary files to the dev
stage.
This commit is contained in:
Ruidy 2025-04-27 14:20:08 +02:00
parent db1fa2cbd9
commit 7038b3e4ae
No known key found for this signature in database
GPG key ID: E00F51288CB857CC

View file

@ -1,18 +1,34 @@
FROM golang:1.24-alpine # ----------- Builder Stage -----------
FROM golang:1.24-alpine AS builder
WORKDIR /app WORKDIR /app
RUN apk update \ RUN apk update && apk add --no-cache build-base
&& apk add --no-cache build-base \
&& apk add --no-cache golangci-lint \
&& go install github.com/air-verse/air@latest \
&& go install github.com/a-h/templ/cmd/templ@latest
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
COPY . . COPY . .
RUN go build -ldflags="-s -w" -o rentease main.go
# Install air and templ for live reload and templating in dev
RUN go install github.com/air-verse/air@latest \
&& go install github.com/a-h/templ/cmd/templ@latest \
&& rm -rf /go/pkg/mod /root/.cache/go-build
# ----------- Dev Stage -----------
FROM golang:1.24-alpine AS dev
WORKDIR /app
# Install runtime dependencies
RUN apk add --no-cache ca-certificates && apk add --no-cache golangci-lint
# Copy only necessary files from builder
COPY --from=builder /app/rentease ./rentease
COPY --from=builder /app/assets ./assets
COPY --from=builder /go/bin/air /go/bin/templ /go/bin/
COPY . .
EXPOSE 8000 EXPOSE 8000
CMD [ "air", "-c", ".air.toml" ] CMD ["air", "-c", ".air.toml"]