Docker构建Python镜像时pip下载依赖超时,求解决方案
解决Docker构建时pip安装依赖超时的问题
换用国内PyPI镜像源
直接在pip安装命令里指定国内镜像源,绕开官方源的网络问题,比如用清华镜像:RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple也可以在容器里配置全局pip源,后续所有pip命令自动使用:
RUN echo "[global]\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple" > /etc/pip.conf RUN pip install --no-cache-dir -r requirements.txt延长pip超时时间
通过--default-timeout参数给pip更长的下载等待时间,比如设置为100秒:RUN pip install --no-cache-dir --default-timeout=100 -r requirements.txt本地预下载依赖再复制进容器
- 先在本地把所有依赖包下载好:
pip download -r requirements.txt -d ./packages - 在Dockerfile里把本地的依赖目录复制进容器,然后从本地安装:
COPY ./packages /packages RUN pip install --no-cache-dir --find-links=/packages -r requirements.txt
- 先在本地把所有依赖包下载好:
更换基础镜像
部分官方Python镜像的网络访问可能受限,试试国内维护的镜像,比如阿里云的:# 替换原有的FROM语句 FROM registry.cn-hangzhou.aliyuncs.com/google_containers/python:3.10-slim也可以尝试alpine轻量镜像(注意alpine需要额外安装编译依赖,比如pandas需要gcc等工具):
FROM python:3.10-alpine RUN apk add --no-cache gcc musl-dev python3-dev RUN pip install --no-cache-dir -r requirements.txt调整Docker构建网络
给build命令加上--network host参数,让构建过程直接使用宿主机网络:docker build --network host -t price_updater_service .(注意:原命令里的镜像名带
.py后缀不规范,建议改成price_updater_service)
内容的提问来源于stack exchange,提问作者HesamHashemi
相关产品推荐
相关产品推荐

