简体   繁体   English

如何在 docker 中运行 venv?

[英]How to run a venv in the docker?

My Dockerfile我的 Dockerfile

FROM python:3.7 AS builder
RUN python3 -m venv /venv

COPY requirements.txt .

RUN /venv/bin/pip3 install -r requirements.txt
FROM python:3.7

WORKDIR /home/sokov_admin/www/bot-telegram

COPY . .

CMD ["/venv/bin/python", "./bot.py"]

When I run the docker image I have this error:当我运行 docker 映像时,出现此错误:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/venv/bin/python": stat /venv/bin/python: no such file or directory: unknown. docker:来自守护进程的错误响应:OCI 运行时创建失败:container_linux.go:380:导致启动容器进程:exec:“/venv/bin/python”:stat /venv/bin/python:没有这样的文件或目录:未知。

What should I change in my code?我应该在我的代码中更改什么?

The example you show doesn't need any OS-level dependencies for Python dependency builds.您展示的示例不需要 Python 依赖项构建的任何操作系统级依赖项。 That simplifies things significantly: you can do things in a single Docker build stage, without a virtual environment, and there wouldn't be any particular benefit from splitting it up.这显着简化了事情:您可以在单个 Docker 构建阶段中完成工作,而无需虚拟环境,并且将其拆分不会有任何特别的好处。

FROM python:3.7
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["./bot.py"]

The place where a multi-stage build with a virtual environment helps is if you need a full C toolchain to build Python libraries.如果您需要完整的 C 工具链来构建 Python 库,那么使用虚拟环境的多阶段构建会有所帮助。 In this case, in a first stage, you install the C toolchain and set up the virtual environment.在这种情况下,在第一阶段,您安装 C 工具链并设置虚拟环境。 In the second stage you need to COPY --from=... the entire virtual environment to the final image.在第二阶段,您需要COPY --from=...整个虚拟环境到最终映像。

# Builder stage:
FROM python:3.7 AS builder

# Install OS-level dependencies
RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive \
    apt-get install --no-install-recommends --assume-yes \
      build-essential
    # libmysql-client-dev, for example

# Create the virtual environment
RUN python3 -m venv /venv
ENV PATH=/venv/bin:$PATH

# Install Python dependencies
WORKDIR /app
COPY requirements.txt .
RUN pip3 install -r requirements.txt

# If your setup.py/setup.cfg has a console script entry point,
# install the application too
# COPY . .
# RUN pip3 install .

# Final stage:
FROM python:3.7 # must be _exactly_ the same image as the builder

# Install OS-level dependencies if needed (libmysqlclient, not ...-dev)
# RUN apt-get update && apt-get install ...

# Copy the virtual environment; must be _exactly_ the same path
COPY --from=builder /venv /venv
ENV PATH=/venv/bin:$PATH

# Copy in the application (if it wasn't `pip install`ed into the venv)
WORKDIR /app
COPY . .

# Say how to run it
EXPOSE 8000
CMD ["./bot.py"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM