[英]Deploying multi-stage Docker image in Google Cloud Run
我创建了一个多阶段 Docker 图像以减小我的 python 应用程序的大小。 Dockerfile的内容是:
FROM python:3.10-slim AS image-compiling
# updates pip and prepare for installing wheels
RUN pip install --upgrade pip && \
pip install wheel && \
pip cache purge
# install needed modules from wheels
RUN pip install --user \
Flask==2.2.2 Flask-RESTful==0.3.9 Flask-Cors==3.0.10 keras==2.9.0 && \
pip cache purge
# brand new image
FROM python:3.10-slim AS image-deploy
# get python 'user environment'
COPY --from=image-compiling /root/.local /root/.local
# get app content
COPY app ./app
# define working directory and the standard command (run it detached)
WORKDIR /app
ENTRYPOINT ["python"]
CMD ["wsgi.py"]
然后我将图像my_image
推送到我的项目my_proj
的谷歌云存储中:
$ docker push us.gcr.io/my_proj/my_image
当我尝试使用此映像启动 Google Cloud Run 服务时,它失败并出现 Python 错误:
Error 2022-09-14 11:41:13.744 EDTTraceback (most recent call last): File "/app/wsgi.py", line 10, in <module> from flask import render_template ModuleNotFoundError: No module named 'flask'
Warning 2022-09-14 11:41:13.805 EDTContainer called exit(1).
但是镜像中安装了flask
,从这个镜像本地创建的容器确实可以正常运行。
为什么 Google Cloud Run 中的容器找不到模块flask
? 它不是完全创建的吗?
问题原因:
在这种情况下,问题不在于图像是使用多阶段方法创建的。 问题是 Python 模块是使用选项--user
安装的。
包含此选项,以便将所需的 Python 模块存储在文件夹/root/.local
中,可以直接将其复制到新的部署映像中。
但是,由于某种原因,Google Cloud Run 中容器中的 Python 应用程序无法找到位于文件夹/root/.local
中的模块。 那里可能使用了root
以外的用户。 因此,使用pip
的--user
参数不起作用,这也抑制了此类场景中的多阶段方法。
解决方案:
使用全局 Python 模块,即 Dockerfile 做一个“单阶段”图像:
FROM python:3.10-slim
# updates pip and prepare for installing wheels
RUN pip install --upgrade pip && \
pip install wheel && \
pip cache purge
# install needed modules from wheels
RUN pip install \
Flask==2.2.2 Flask-RESTful==0.3.9 Flask-Cors==3.0.10 keras==2.9.0 && \
pip cache purge
# get app content
COPY app ./app
# define working directory and the standard command (run it detached)
WORKDIR /app
ENTRYPOINT ["python"]
CMD ["wsgi.py"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.