Docker 带有 golang 的容器 http.Get 错误 "certificate signed by unknown authority"

Docker Container with golang http.Get error "certificate signed by unknown authority"

我有一个调用 https api 的 Golang 容器。我正在使用临时容器,当我尝试 运行 我得到一个 certificate signed by unknown authority

url := "https://restcountries.eu/rest/v2/name/" + params.Get("country")
response, err := http.Get(url)

我的Dockerfile是这样的:

FROM golang:1.15 AS builder
WORKDIR /GreetingAPI
COPY . /greeting
WORKDIR /greeting
ENV GO111MODULE=on
RUN CGO_ENABLED=0 GOOS=linux go build -o greeting

FROM scratch
COPY --from=builder /greeting .
CMD ["./greeting"]

我使用这个 answare 更新了我的 Dockerfile。但是当我尝试构建容器时,我得到 ERROR: "/ca-certificates.crt" not found: not foundfailed to solve: rpc error: code = Unknown desc = failed to compute cache key: "/ca-certificates.crt" not found: not found

FROM golang:1.15 AS builder
WORKDIR /GreetingAPI
COPY . /greeting
WORKDIR /greeting
ENV GO111MODULE=on
RUN CGO_ENABLED=0 GOOS=linux go build -o greeting

FROM scratch
ADD ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /greeting .
CMD ["./greeting"]

在您的构建器阶段安装 ca cert 并复制到最终映像。类似于:

FROM golang:1.15 AS builder
RUN apk update
RUN apk add -U --no-cache ca-certificates && update-ca-certificates
WORKDIR /GreetingAPI
COPY . /greeting
WORKDIR /greeting
ENV GO111MODULE=on
RUN CGO_ENABLED=0 GOOS=linux go build -o greeting

FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /greeting .
CMD ["./greeting"]

我可能需要在链接的答案中说得更清楚,第一个示例中的副本是一个单阶段示例,其中您有一个证书文件要注入您的构建上下文(通常包含您的 Dockerfile 的目录):

FROM scratch
ADD ca-certificates.crt /etc/ssl/certs/
ADD main /
CMD ["/main"]

您有一个多阶段构建,可以按照链接答案后半部分的多阶段方法进行操作。这会在分发供应商的另一个阶段安装证书并将它们复制到您的临时阶段:

FROM golang:alpine as build
RUN apk --no-cache add ca-certificates
WORKDIR /go/src/app
COPY . .
RUN CGO_ENABLED=0 go-wrapper install -ldflags '-extldflags "-static"'

FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /go/bin/app /app
ENTRYPOINT ["/app"]

但是,第二个示例假设 Alpine 作为第一阶段的基础,使用 apk。 (它还假定证书需要安装在基本映像中,但事实证明在当前的 golang 映像中并非如此。)对于您的示例,它基于 golang:1.15 映像中的 Debian。为此,您通常需要 apt-get 命令,但在这种情况下 ca-certificates 包已经安装,因此您只需复制结果:

FROM golang:1.15 AS builder
COPY . /greeting
WORKDIR /greeting
ENV GO111MODULE=on
RUN CGO_ENABLED=0 GOOS=linux go build -o greeting

FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /greeting /
CMD ["/greeting"]