【发布时间】:2019-09-14 06:57:11
【问题描述】:
我正在尝试使用 Python 中的 grpc 服务创建小型 docker 映像。为了了解大小,我构建了一个基本的 hello-world Python grpc 服务。为了保持“小”,我使用了多阶段构建,从 python:3.7-alpine 开始,然后
1) 为最终的 python 安装创建一个 virtualenv
2) 为 grpc 和 protobuf 添加必要的构建包
3) 将 virtualenv 复制到基础安装中
4) 复制应用文件
docker文件如下:
FROM python:3.7-alpine as base
FROM base as builder
RUN adduser -D webuser
WORKDIR /home/webuser
RUN apk add --update \
gcc \
g++ \
make \
musl-dev \
python3-dev \
libc6-compat \
&& rm -rf /var/cache/apk/*
# create a virtual env
RUN python -m venv env
# install all requirements
RUN env/bin/pip install protobuf grpcio
FROM base
RUN adduser -D webuser
WORKDIR /home/webuser
COPY --from=builder /home/webuser/env/ env/
# copy the app files
COPY hello/gen-py/ ./
COPY hello/hello.py ./
COPY boot.sh ./
# make webuser the owner of the main folder
RUN chown -R webuser:webuser ./
# activate webuser
USER webuser
# boot.sh is the executable script that basically runs python
# from the env with the grpc server hello.py
RUN chmod +x boot.sh
EXPOSE 50051
ENTRYPOINT ["./boot.sh"]
就我的尺寸而言:
python:3.7-alpine 87MB
"builder" 396MB
hello_app:latest 188MB
这仍然是一个非常大的 hello world 应用程序。我用 C++ 构建了一个类似的,只有 12.4MB。关于尺寸,我不明白一些事情
我的环境为 51.1 MB,基础 python 为 93.5MB(基于 python:3.7-alpine 上的 du -sh。我不清楚为什么这比 docker image ls 中报告的 87MB 大)。总共是 144.6MB,但仍报告为 188MB。
我的主要问题:如何以尽可能少的开销创建 Python GRPC 服务? 其他问题:谁能解释 docker 的大小?为什么只添加了 50MB 的虚拟 env 时,docker 会向基础映像报告 + 100MB。
【问题讨论】:
-
hello/gen-py/中有什么
-
hello_pb2.py hello_pb2_grpc.py
-
运行
docker history <your_image_id_or_name>,您将看到所有内容的确切来源。欲了解更多信息,请查看:docs.docker.com/engine/reference/commandline/history -
是的,docker 历史对此非常有用!
标签: python docker grpc-python