跳到主要内容

Go 应用

FROM golang:1.24.4-alpine AS build-env

RUN ln -s /var/cache/apk /etc/apk/cache
RUN --mount=type=cache,target=/var/cache/apk,id=apk-cache \
--mount=type=cache,target=/root/.cache/go-build,id=go-build-cache \
sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
&& apk update --no-cache \
&& apk add --no-cache git make

ENV GOSUMDB=off \
GO111MODULE=on \
CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64 \
GOPROXY="https://mirrors.aliyun.com/goproxy,direct"

WORKDIR /workspace

COPY go.mod go.sum ./

RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod-cache,sharing=locked \
go mod download

COPY . .

RUN --mount=type=cache,target=/go/pkg/mod,id=go-mod-cache,sharing=locked \
--mount=type=cache,target=/root/.cache/go-build,id=go-build-cache \
go build -ldflags='-extldflags "-static" -s -w' -o /bin/server main.go

FROM alpine:3.14.0

RUN ln -s /var/cache/apk /etc/apk/cache
RUN --mount=type=cache,target=/var/cache/apk,id=apk-cache \
sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
&& apk update --no-cache \
&& apk add --no-cache ca-certificates tzdata bash curl

RUN addgroup -S server && adduser -S server -G server

USER server

COPY --from=build-env /bin/server /server

ENV GIN_MODE=release
EXPOSE 8080
ENTRYPOINT [ "/server" ]