如何在docker中运行一个venv?

How to run a venv in the docker?

我的 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"]

当我 运行 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.

我应该在我的代码中更改什么?

您展示的示例不需要任何 OS 级别的依赖项来构建 Python 依赖项。这大大简化了事情:您可以在单个 Docker 构建阶段完成任务,无需虚拟环境,并且将其拆分不会有任何特别的好处。

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

如果您需要完整的 C 工具链来构建 Python 库,那么使用虚拟环境进行多阶段构建会有所帮助。在这种情况下,在第一阶段,您安装 C 工具链并设置虚拟环境。在第二阶段你需要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"]