Docker build 如何在golang build中添加库

fre*_*czj 4 go docker dockerfile apache-pulsar

我正在构建一个处理 Apache Pulsar 的 GO 应用程序。Go 客户端需要 C++ 库,正如 Pulsar 文档所要求的那样(顺便说一句,Kafka 也是如此)。

我想把所有这些都打包成一个尽可能小的容器。我通常使用 SCRATCH 并从另一个基于 golang 的容器中复制输出。不幸的是,我无法从这个初始容器中获取外部库:

FROM golang:latest as builder
ENV GO111MODULE=on \
CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
ARG DOCKER_GIT_CREDENTIALS
WORKDIR /builder
ADD . /builder
RUN git config --global credential.helper store && echo "${DOCKER_GIT_CREDENTIALS}" > ~/.git-credentials
RUN make build
RUN echo $(go list -m) && mv bin/$(go list -m) app

FROM SCRATCH
COPY --from=builder /builder/app app
EXPOSE 8080
ENTRYPOINT ["./app"]
Run Code Online (Sandbox Code Playgroud)

使用它会使构建失败,寻找丢失的符号

/go/pkg/mod/github.com/apache/pulsar/pulsar-client-go@v0.0.0-20200118070759-21660e9402f8/pulsar/client.go:29:9: undefined: newClient
...
Run Code Online (Sandbox Code Playgroud)

而本地构建工作。

如何正确集成我需要的库?

Min*_* L. 6

由于您使用的库具有 C++ lib 依赖项,因此要正确构建 Pulsar Golang 客户端 docker 映像,您需要使用 Docker 阶段构建。我们有确切的用例。您需要下载并安装 Pulsar C++ lib 以在Dockerfile.

这是我们的 docker 文件https://github.com/kafkaesque-io/pulsar-beam/blob/master/Dockerfile。我还建议使用 Go Module 来构建和管理 Go 依赖项,作为 Docker 阶段构建的一部分。这是我们的做法。我希望它有帮助。

RUN wget --user-agent=Mozilla -O apache-pulsar-client.deb "https://archive.apache.org/dist/pulsar/pulsar-2.4.1/DEB/apache-pulsar-client.deb"
RUN wget --user-agent=Mozilla -O apache-pulsar-client-dev.deb "https://archive.apache.org/dist/pulsar/pulsar-2.4.1/DEB/apache-pulsar-client-dev.deb"

RUN apt install -y ./apache-pulsar-client.deb
RUN apt install -y ./apache-pulsar-client-dev.deb

# Copy go mod and sum files
COPY go.mod go.sum ./

# Download all dependencies. Dependencies will be cached if the go.mod and go.sum files are not changed
RUN go mod download
Run Code Online (Sandbox Code Playgroud)

我使用标准的 ubuntu 映像进行构建和运行时映像。我了解您正在寻找尽可能小的图像尺寸。ubuntu:18.04占地面积更小。您也可以尝试我尚未测试的 alpine。

顺便说一下,Apache 提供了一个独立的原生 Pulsar Go 客户端库,没有 C++ 依赖。在 2020 年 1 月撰写本文时,仍然缺少分区主题的自定义路由模式等功能。如果您的项目不需要这些功能,我建议您尝试使用原生 Go 客户端库以避免 C++ 依赖。出于同样的原因,我们计划很快切换到新的本地库。