无法使用Distroless容器镜像部署Flask应用问题排查
问题分析与解决:Distroless Python镜像中找不到Flask依赖
问题根源
你在多阶段构建的builder阶段用pip install安装的依赖,默认会放到Ubuntu系统的Python包路径(比如/usr/local/lib/python3.8/site-packages),但你只复制了/test目录到distroless镜像,系统级的依赖包并没有被复制过去,所以distroless里的Python找不到Flask。
解决方案:将依赖安装到项目目录并设置PYTHONPATH
修改builder阶段的pip命令,把依赖安装到项目内的指定目录,这样复制项目文件时就能一并带上依赖,再通过环境变量让Python识别这个路径。
修改后的完整Dockerfile:
################################ # First stage: build environment ################################ FROM ubuntu:20.04 AS builder # Set working directory WORKDIR /test # Copy all files to the working directory COPY . /test # Install dependencies into a local directory inside the project RUN apt-get update && \ apt-get install -y python3 python3-pip && \ pip install --target=/test/deps -r requirements.txt ########################################################## # Second stage: runtime environment using distroless image ########################################################## FROM gcr.io/distroless/python3-debian10 # Set working directory WORKDIR /test # Copy project files and local dependencies from builder stage COPY --from=builder /test /test # Set PYTHONPATH to include the local dependencies directory ENV PYTHONPATH=/test/deps # Run the application ENTRYPOINT ["python3"] CMD ["app.py"]
关键修改说明
pip install --target=/test/deps -r requirements.txt:将所有依赖包安装到项目目录下的deps文件夹,而不是系统路径ENV PYTHONPATH=/test/deps:告诉Python在这个目录下查找第三方包- 保持COPY命令不变,因为现在
/test已经包含了项目代码和依赖
验证建议
构建并运行后,可通过以下命令进入容器验证依赖是否存在:
docker exec -it <container-id> /bin/sh # 进入后执行 python3 -c "import flask; print(flask.__version__)"
内容的提问来源于stack exchange,提问作者Bandhan Majumder
相关产品推荐
相关产品推荐

