Ubuntu 20.04环境下Docker容器连接PyPI超时问题求助
解决Docker构建时pip连接PyPI超时的问题
针对你遇到的pip安装依赖时连接PyPI超时(ReadTimeoutError)的问题,提供以下几种可行的解决方案:
1. 延长pip超时时间
默认pip的超时时间为15秒,网络条件不佳时容易触发超时。修改Dockerfile中的pip安装命令,增加超时参数:
RUN pip3 install --no-cache-dir --timeout=60 -r requirements.txt
可根据实际网络情况调整超时数值,给网络请求预留足够的完成时间。
2. 切换国内PyPI镜像源
国内镜像源访问速度更快,能大幅降低超时概率。可以直接在pip命令中指定源:
RUN pip3 install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
也可以提前配置pip默认使用国内源,避免每次命令重复加参数:
FROM python:3.10 WORKDIR / ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # 配置清华PyPI镜像源 RUN mkdir -p ~/.pip && echo "[global]\nindex-url = https://pypi.tuna.tsinghua.edu.cn/simple" > ~/.pip/pip.conf COPY . . RUN pip3 install --no-cache-dir -r requirements.txt CMD python main.py
3. 排查宿主机网络连通性
先确认Ubuntu 20.04宿主机本身能正常访问PyPI:
curl -I https://pypi.org/simple/aiofiles/
如果宿主机也出现超时,说明是宿主机网络问题,需要检查防火墙规则、代理设置或网络运营商限制。
4. 调整Docker容器DNS配置
DNS解析异常也可能导致连接超时。在docker-compose.yml的telegram-bot服务中添加公共DNS服务器:
telegram-bot: container_name: telegram-bot build: context: ./bot_elephant volumes: - ./bot_elephant env_file: - ./bot_elephant/.env depends_on: - postgres dns: - 8.8.8.8 - 114.114.114.114
内容的提问来源于stack exchange,提问作者Fastroer
相关产品推荐
相关产品推荐

