换了镜像源,下载还是慢——这是开发环境配置时最常见的困惑。问题不总在镜像本身,可能是配置没生效、包没同步、或者瓶颈根本不在包下载这一步。
镜像 vs 代理:先搞清楚用的是哪种
镜像(Mirror):
你 → 国内镜像服务器(已有副本)→ 直接返回
速度:快,延迟低,不依赖境外网络
代理(Proxy):
你 → 代理服务器 → 境外官方源 → 代理转发回来
速度:取决于代理出口带宽,通常比直连好但不如镜像
最常见的错误:同时设了 HTTP_PROXY(翻墙代理)和镜像源,结果镜像域名的请求也走了代理,绕了一大圈反而变慢。
排查是否走了代理:
# 看当前环境变量
echo $HTTP_PROXY $HTTPS_PROXY $ALL_PROXY
# 临时取消代理测试
unset HTTP_PROXY HTTPS_PROXY ALL_PROXY
pip install somepackage -i https://mirrors.aliyun.com/pypi/simple/
pip 换源
永久生效
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
pip config set global.trusted-host mirrors.aliyun.com
手动编辑配置文件
~/.config/pip/pip.conf(Linux/macOS)或 %APPDATA%\pip\pip.ini(Windows):
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com
验证生效
pip config list
# 应显示:global.index-url = https://mirrors.aliyun.com/pypi/simple/
pip install requests -v 2>&1 | grep "Looking in indexes"
# 应显示镜像地址
常用 PyPI 镜像
| 镜像 | 地址 |
|---|---|
| 阿里云 | https://mirrors.aliyun.com/pypi/simple/ |
| 腾讯云 | https://mirrors.cloud.tencent.com/pypi/simple/ |
| 清华大学 | https://pypi.tuna.tsinghua.edu.cn/simple/ |
| 中科大 | https://pypi.mirrors.ustc.edu.cn/simple/ |
npm / pnpm 换源
# npm 永久换源
npm config set registry https://registry.npmmirror.com
# pnpm 永久换源(共用 ~/.npmrc)
pnpm config set registry https://registry.npmmirror.com
# 验证
npm config get registry
# 单次使用镜像
npm install --registry=https://registry.npmmirror.com
postinstall 下载二进制的坑
Puppeteer、Electron、node-sass 等在 npm install 后还会下载平台二进制,这不走 npm 镜像:
# Puppeteer
npm config set PUPPETEER_DOWNLOAD_HOST https://npmmirror.com/mirrors
# Electron
npm config set ELECTRON_MIRROR https://npmmirror.com/mirrors/electron/
# node-sass
npm config set sass_binary_site https://npmmirror.com/mirrors/node-sass/
Maven 换源
~/.m2/settings.xml:
<settings>
<mirrors>
<mirror>
<id>aliyun</id>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
</settings>
验证:mvn help:effective-settings | grep url,应该看到镜像 URL。
注意:<mirrorOf>central</mirrorOf> 只代理 Maven Central,如果项目用了 Spring、JBoss 等其他仓库,需要单独配置或用 <mirrorOf>*</mirrorOf>(代理所有,但可能导致私有仓库也被代理)。
Go 换源
# 永久设置(写入 GOENV)
go env -w GOPROXY=https://goproxy.cn,direct
# direct 是回退策略:镜像没有时直连官方
# 验证
go env GOPROXY
Cargo(Rust)换源
~/.cargo/config.toml:
[source.crates-io]
replace-with = "ustc"
[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"
换源后还是慢的排查清单
1. 确认配置文件路径正确(用户级 vs 项目级)
2. 确认没有代理环境变量覆盖(echo $HTTP_PROXY)
3. ping 镜像域名,看延迟和是否可达
4. 检查包是否在镜像里存在(新包同步有延迟)
5. 看是否有 postinstall 脚本在下载二进制(npm/pip 详情日志)
6. CI 环境检查是否缓存了依赖目录
配套工具
- 公共 DNS 速查 — 镜像域名解析慢时换 DNS
- TCP/UDP 端口表 — 包管理器走的端口(pip/npm 用 443)
- IP 工具箱 — 查镜像服务器 IP 是否在国内