选择 Golang docker 基础镜像

Choosing Golang docker base image

图像 golangalpine 的大小相差大约 300Mb

使用 golang 图片而不是普通 alpine 有什么好处?

简短回答:比较 golang:alpinealpine 之间的差异会更公平。

在撰写本文时,golang 映像是基于 Debian 构建的,与 Alpine 不同。 I'll quote the documentation from Docker Hub:

golang:<version>

This is the defacto image. If you are unsure about what your needs are, you probably want to use this one. It is designed to be used both as a throw away container (mount your source code and start the container to start your app), as well as the base to build other images off of.

golang:alpine

This image is based on the popular Alpine Linux project, available in the alpine official image. Alpine Linux is much smaller than most distribution base images (~5MB), and thus leads to much slimmer images in general.

This variant is highly recommended when final image size being as small as possible is desired. The main caveat to note is that it does use musl libc instead of glibc and friends, so certain software might run into issues depending on the depth of their libc requirements. However, most software doesn't have an issue with this, so this variant is usually a very safe choice. See this Hacker News comment thread for more discussion of the issues that might arise and some pro/con comparisons of using Alpine-based images.

总而言之,基于 Alpine 构建的映像往往比 Debian 的要小。但是,它们不会包含您可能会发现对开发和调试有用的各种系统工具。一个常见的折衷方案是构建具有 golang 风格的二进制文件,并使用 golang:alpinealpine 或如上面评论中所述 scratch.[= 部署到生产环境中22=]

为什么不scratch

您可以构建一个静态 go 二进制文件并将其复制到 docker 映像中。

docker 图像的大小将等于二进制文件的大小。

假设你的go二进制文件名为main_go,这是你需要的Dockerfile

FROM centurylink/ca-certs
ADD main_go /
CMD ["/main_go"]

请记住 scratchcenturylink 是空白图像,因此您必须使用所有内置库静态编译您的应用程序。

示例:

CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main_go .

Here you can find some extra info about docker, go and scratch and here 你可以找到一些关于 GOOS 值的信息。

更新:使用 alpine 构建映像的多阶段构建。

ARG GO_VERSION=1.15.6
 
# STAGE 1: building the executable
FROM golang:${GO_VERSION}-alpine AS build
RUN apk add --no-cache git
RUN apk --no-cache add ca-certificates
 
# add a user here because addgroup and adduser are not available in scratch
RUN addgroup -S myapp \
    && adduser -S -u 10000 -g myapp myapp
 
WORKDIR /src
COPY ./go.mod ./go.sum ./
RUN go mod download
 
COPY ./ ./
 
# Run tests
RUN CGO_ENABLED=0 go test -timeout 30s -v github.com/gbaeke/go-template/pkg/api
 
# Build the executable
RUN CGO_ENABLED=0 go build \
    -installsuffix 'static' \
    -o /app ./cmd/app
 
# STAGE 2: build the container to run
FROM scratch AS final
LABEL maintainer="gbaeke"
COPY --from=build /app /app
 
# copy ca certs
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
 
# copy users from builder (use from=0 for illustration purposes)
COPY --from=0 /etc/passwd /etc/passwd
 
USER myapp
 
ENTRYPOINT ["/app"]

可以找到更多信息 here