登录
首页 >  Golang >  Go问答

如何在golang支持的gRPC中减少docker镜像的大小?

来源:stackoverflow

时间:2024-03-16 17:51:24 180浏览 收藏

在 Golang 中使用 gRPC 时,容器化应用程序可能会导致 Docker 镜像大小过大。通过使用多级 Docker 镜像,可以将构建过程与最终镜像分离开来,从而减少镜像大小。多级镜像允许在单独的构建阶段进行 protobuf 编译和 Go 构建,然后将结果复制到更小的基础镜像中,从而显著缩小最终镜像的大小。

问题内容

我有一些使用 grpc/golang 进行通信的服务器和客户端。现在我想容器化我的应用程序,但包含 goland 执行和 grpc 支持的 docker 镜像的大小更大(超过 1gb)。我想减小泊坞窗图像的大小。

所需的golang版本是1.9及更高版本。这里给出了 dockerfile 脚本。如果还有其他方法请推荐。

FROM golang:1.11

RUN apt-get update && \
    apt-get -y install git unzip build-essential autoconf libtool

RUN git clone https://github.com/google/protobuf.git && \
    cd protobuf && \
    ./autogen.sh && \
    ./configure && \
    make && \
    make install && \
    ldconfig && \
    make clean && \
    cd .. && \
    rm -r protobuf

RUN go get google.golang.org/grpc

RUN go get github.com/golang/protobuf/protoc-gen-go

RUN ls -la

WORKDIR /helloworld

COPY . /helloworld

RUN protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld

CMD ["go", "run", "helloworld/greeter_server/main.go"]

解决方案


尝试制作像这样的多级docker镜像

# Compile stage
FROM golang:1.11 as build-env

RUN apt-get update && \
    apt-get -y install git unzip build-essential autoconf libtool

RUN git clone https://github.com/google/protobuf.git && \
    cd protobuf && \
    ./autogen.sh && \
    ./configure && \
    make && \
    make install && \
    ldconfig && \
    make clean && \
    cd .. && \
    rm -r protobuf

RUN go get google.golang.org/grpc

RUN go get github.com/golang/protobuf/protoc-gen-go

RUN ls -la

WORKDIR /helloworld

COPY . /helloworld

RUN protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
RUN go build -o server helloworld/greeter_server/main.go

# Making image
FROM alpine:3.8 AS host
RUN apk add --no-cache \
        ca-certificates
COPY --from=build-env /helloworld/server /
# copy any other files you need

WORKDIR /
EXPOSE 8000
CMD ["server"]

您可以尝试使用 distroless 基础映像和多阶段构建。这可能对你有帮助。

本篇关于《如何在golang支持的gRPC中减少docker镜像的大小?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>