Skip to content

Commit

Permalink
Merge pull request #514 from catatsuy/feature-update-golang-dockerfile
Browse files Browse the repository at this point in the history
Refactor Dockerfile to use multi-stage builds and add caching mechanisms
  • Loading branch information
catatsuy authored Aug 11, 2024
2 parents 447d5ff + 684c71a commit 4148419
Showing 1 changed file with 49 additions and 9 deletions.
58 changes: 49 additions & 9 deletions webapp/golang/Dockerfile
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" ]

0 comments on commit 4148419

Please sign in to comment.