我最近一直在研究 docker 镜像。我看到这个 docker 文档关于使用FROM scratch
. 我想看看我能走多远,只是为了好玩。我用Python编程。该文档说将示例 C 程序编译为二进制文件,将其复制到容器中,然后运行它。在容器中,我无法运行python <program_file>.
我看到了有关将 python 文件编译为二进制文件的堆栈交换帖子,这符合我们的测试用例。它提到使用pyinstaller
. 因此,我在一个测试文件上运行它hello.py
,该文件仅打印 Hello with pyinstaller hello.py
,并且收到一堆有关构建项目的消息。好的。我可以通过运行“dist/hello”在本地计算机中运行二进制文件(这是帖子中提到的二进制程序。所以我编写了 Dockerfile 来复制该程序并运行它。我的 Dockerfile 是
FROM scratch
ADD dist/hello /
CMD ["./hello"]
Run Code Online (Sandbox Code Playgroud)
我运行docker build . -t "hello:1.0"
然后docker run hello:1.0
......我收到一条错误消息:
standard_init_linux.go:211: exec user process caused "no such file or directory"
Run Code Online (Sandbox Code Playgroud)
是什么赋予了?我做错了什么?是否可以让 pyinstaller 编译一个二进制 python 项目(多个文件,而不仅仅是这个文件),然后使用临时映像来运行它。如果可能的话,有什么注意事项吗?
所以答案是使用 Google 的 distroless 镜像。他们的 github 上有一个示例,我稍作编辑如下:
# Build a virtualenv using the appropriate Debian release
# * Install python3-venv for the built-in Python3 venv module (not installed by default)
# * Install gcc libpython3-dev to compile C Python modules
# * Update pip to support bdist_wheel
FROM debian:buster-slim AS build
RUN apt-get update && \
apt-get install --no-install-suggests --no-install-recommends --yes python3-venv gcc libpython3-dev && \
python3 -m venv /venv && \
/venv/bin/pip install --upgrade pip
# Build the virtualenv as a separate step: Only re-execute this step when requirements.txt changes
FROM build AS build-venv
COPY requirements.txt /requirements.txt
RUN /venv/bin/pip install --disable-pip-version-check -r /requirements.txt
# Copy the virtualenv into a distroless image
FROM gcr.io/distroless/python3-debian10
COPY --from=build-venv /venv /venv
COPY . /app
WORKDIR /app
ENTRYPOINT ["/venv/bin/python3", "hello.py"]
Run Code Online (Sandbox Code Playgroud)
只是发布这个以防有人想知道。绝对是一件很酷的事情。