WSL2(Ubuntu22.04)下Docker构建镜像pip安装asgiref超时失败求助
pip安装超时失败的原因及解决办法
问题场景
在Windows 11的WSL 2(Ubuntu 22.04)环境下,使用Docker 20.10.19构建Python镜像时,执行RUN pip install -r requirements.txt步骤出现ReadTimeoutError,无法完成asgiref==3.5.2的安装,错误信息如下:
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/
可能原因
- 网络访问受限:WSL 2或Docker容器的网络链路存在问题,比如本地网络波动、Windows防火墙/代理拦截了对pypi.org的HTTPS请求,或是WSL 2的网络配置异常导致容器无法正常连接外网。
- pip默认超时阈值过短:pip默认的读取超时时间为15秒,当网络延迟较高或PyPI服务器响应缓慢时,很容易触发超时重试,最终导致安装失败。
- 基础镜像DNS解析异常:使用的
python:3.10.6-slim-bullseye镜像可能存在DNS配置问题,无法正确解析pypi.org的域名,进而引发连接超时。
解决建议
切换国内PyPI镜像源
修改Dockerfile中的pip安装命令,指定国内镜像(如清华镜像),大幅提升下载速度:RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple延长pip超时时间
通过--default-timeout参数增加超时阈值,给网络请求更多缓冲时间:RUN pip install --default-timeout=60 -r requirements.txt排查WSL 2网络配置
- 在WSL 2终端中执行
ping pypi.org测试网络连通性; - 检查Windows防火墙是否允许WSL 2和Docker的网络访问;
- 重置WSL 2网络:
wsl --shutdown # 重启WSL后重新执行镜像构建
- 在WSL 2终端中执行
检查Docker网络设置
确保Docker默认的bridge网络模式能正常访问外网,必要时可尝试重启Docker服务后再构建镜像。
内容的提问来源于stack exchange,提问作者Bogdan Kozlovskyi
相关产品推荐
相关产品推荐

