DNS解析失败导致“Could not resolve host”,须优先排查DNS配置、hosts文件、nsswitch.conf、systemd-resolved服务及临时指定DNS,而非调整超时或Composer镜像配置。

直接换 DNS 或绑 hosts,别调 timeout——DNS 失败时改 http.timeout 完全无效。
看到 "Could not resolve host" 就该停在 DNS 层排查
这类错误和 Composer 配置、PHP 超时、镜像地址末尾斜杠都无关,本质是系统根本查不到 packagist.org 或镜像域名(如 mirrors.aliyun.com)的 IP。常见现象包括:
-
composer install卡在Resolving dependencies...后无响应 - 报错明确含
Could not resolve host: packagist.org或Unknown host -
ping packagist.org返回unknown host,但ping 137.74.169.73(已知有效 IP)能通
此时所有 http.timeout、process-timeout、清缓存、换镜像源的操作都是徒劳——连接还没发出去,就卡在“名字认不出来”这一步。
用 nslookup 快速确认是不是 DNS 污染
别猜,两行命令立刻定位:
- 执行
nslookup mirrors.aliyun.com 1.1.1.1:如果返回 IPv4 地址(比如223.5.5.5),说明干净 DNS 可解析,你本地 DNS 被污染 - 执行
nslookup mirrors.aliyun.com(不带 DNS 服务器):如果超时或报*** Can't find mirrors.aliyun.com: Non-existent domain,就是污染实锤
只要第一条通、第二条不通,问题就锁定在 DNS 层,下一步直接改 hosts 或系统 DNS。
hosts 绑定是最稳的落地方式,但三处必须同时做对
尤其适合 CI/CD、Docker 容器、公司内网等无法随意改系统 DNS 的场景:
- IP 必须最新:运行
dig mirrors.aliyun.com @8.8.8.8 +short | head -n1拿当前真实 IP,别抄网上过期的 - 格式必须严格:Linux/macOS 编辑
/etc/hosts,Windows 编辑C:\Windows\System32\drivers\etc\hosts,写成223.5.5.5 mirrors.aliyun.com(IP 和域名之间只能是空格,不能是 Tab 或中文符号) - 缓存必须刷新:macOS 执行
sudo dscacheutil -flushcache,Windows 执行ipconfig /flushdns,Linux systemd 系统执行sudo systemd-resolve --flush-caches
杀毒软件(如火绒、360)常锁死 hosts 文件,保存失败时务必右键编辑器选“以管理员身份运行”。
Docker 容器里 DNS 失败要单独处理
容器默认继承宿主机 DNS,但很多企业网络下宿主机 DNS 本身就被污染,容器内更甚。不能只改宿主机 hosts:
- 启动时显式指定 DNS:
docker run --dns 8.8.8.8 --dns 114.114.114.114 your-image composer install - 或在
/etc/docker/daemon.json中全局配置:{"dns": ["8.8.8.8", "114.114.114.114"]},然后sudo systemctl restart docker
注意:Docker Desktop for Mac/Windows 的 WSL2 后端也需同步检查 WSL2 的 /etc/resolv.conf 是否被覆盖为错误 DNS。
真正麻烦的是你以为 DNS 通了,结果 curl -I https://mirrors.aliyun.com/composer/packages.json 却报 SSL 错误——那说明你绑的 IP 对应的服务证书不匹配,得换另一个 IP 或切回 DNS 方案。这种细节,不试一遍根本想不到。


















