-
Notifications
You must be signed in to change notification settings - Fork 284
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #514 from catatsuy/feature-update-golang-dockerfile
Refactor Dockerfile to use multi-stage builds and add caching mechanisms
- Loading branch information
Showing
1 changed file
with
49 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,52 @@ | ||
FROM golang:1.22 | ||
# syntax=docker/dockerfile:1 | ||
|
||
RUN mkdir -p /home/webapp | ||
WORKDIR /home/webapp | ||
FROM --platform=$BUILDPLATFORM golang:1.22 AS build | ||
WORKDIR /src | ||
|
||
COPY go.mod /home/webapp/go.mod | ||
COPY go.sum /home/webapp/go.sum | ||
RUN go mod download | ||
RUN --mount=type=cache,target=/go/pkg/mod/ \ | ||
--mount=type=bind,source=go.sum,target=go.sum \ | ||
--mount=type=bind,source=go.mod,target=go.mod \ | ||
go mod download -x | ||
|
||
COPY . /home/webapp | ||
RUN go build -o app | ||
CMD ./app | ||
# This is the architecture you’re building for, which is passed in by the builder. | ||
# Placing it here allows the previous steps to be cached across architectures. | ||
ARG TARGETARCH | ||
|
||
# Build the application. | ||
# Leverage a cache mount to /go/pkg/mod/ to speed up subsequent builds. | ||
# Leverage a bind mount to the current directory to avoid having to copy the | ||
# source code into the container. | ||
RUN --mount=type=cache,target=/go/pkg/mod/ \ | ||
--mount=type=bind,target=. \ | ||
CGO_ENABLED=0 GOARCH=$TARGETARCH go build -o /bin/server . | ||
|
||
################################################################################ | ||
FROM alpine:3.20 AS final | ||
|
||
# Install any runtime dependencies that are needed to run your application. | ||
# Leverage a cache mount to /var/cache/apk/ to speed up subsequent builds. | ||
RUN --mount=type=cache,target=/var/cache/apk \ | ||
apk --update add \ | ||
ca-certificates \ | ||
tzdata \ | ||
&& \ | ||
update-ca-certificates | ||
|
||
# Create a non-privileged user that the app will run under. | ||
# See https://docs.docker.com/go/dockerfile-user-best-practices/ | ||
ARG UID=10001 | ||
RUN adduser \ | ||
--disabled-password \ | ||
--gecos "" \ | ||
--home "/nonexistent" \ | ||
--shell "/sbin/nologin" \ | ||
--no-create-home \ | ||
--uid "${UID}" \ | ||
appuser | ||
USER appuser | ||
|
||
# Copy the executable from the "build" stage. | ||
COPY --from=build /bin/server /bin/ | ||
|
||
# What the container should run when it is started. | ||
ENTRYPOINT [ "/bin/server" ] |