“Could not resolve host”本质是DNS解析失败,需优先改DNS或hosts硬解析,再配镜像;IPv6 fallback会导致静默卡顿,应禁用IPv6或强制IPv4。

“Could not resolve host”不是 Composer 配置错了,是系统根本没拿到域名对应的 IP——先改 DNS 或写死 hosts,再谈镜像和超时。
为什么 ping packagist.org 返回 unknown host
这说明系统在 DNS 解析层就失败了,composer install 连第一步都迈不出去。此时调 http.timeout、换镜像源、清缓存全无效。
- 运行
nslookup packagist.org或dig packagist.org,若无 IPv4 地址返回,确认是 DNS 问题 - 立刻换公共 DNS:Linux/macOS 编辑
/etc/resolv.conf,加一行nameserver 114.114.114.114;Windows 在网络适配器中手动设置 - 禁用
systemd-resolved(Linux):sudo systemctl stop systemd-resolved && sudo systemctl disable systemd-resolved,否则它会覆盖/etc/resolv.conf - 验证是否生效:
ping -c 1 packagist.org能看到 IP 才算成功
如何用 /etc/hosts 绕过所有 DNS 污染
当公共 DNS 也返回错误 IP(比如把 github.com 解到拦截页),或者你在 CI/CD 环境里需要绝对稳定,直接硬编码 IP 是唯一可靠方案。
- 查真实 IP:用境外服务器或手机热点执行
curl -I https://packagist.org 2>&1 | grep "Connected to",提取括号内 IPv4 地址(例如137.74.169.73) - 编辑
/etc/hosts(Linux/macOS)或C:\Windows\System32\drivers\etc\hosts(Windows),追加:137.74.169.73 packagist.org - 别漏依赖域名:
223.6.6.6 github.com和223.6.6.6 githubusercontent.com也要加,否则git clone仍卡住 - 刷新本地 DNS 缓存:
sudo dscacheutil -flushcache(macOS)、ipconfig /flushdns(Windows)、sudo systemd-resolve --flush-caches(Linux systemd)
IPv6 fallback 导致“卡住但不报错”怎么破
Composer 默认先试 IPv6,单次超时 1–3 秒,上百个包叠加就是几分钟假性卡顿,日志里却静默无输出——这是最常被忽略的性能黑洞。
- 验证是否存在:
curl -v https://packagist.org 2>&1 | grep "Connected to",若看到类似Connected to packagist.org (2a03:2880:...)后卡住,就是 IPv6 问题 - 临时绕过:
curl -4 -I https://packagist.org强制走 IPv4,看是否立即响应 - 根治方法:Linux 上执行
sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1;Docker 启动时加--dns 8.8.8.8;CI 脚本开头加export COMPOSER_NO_IPV6=1 - 注意:某些内网环境即使禁用 IPv6,
getaddrinfo()仍可能触发 fallback,此时 hosts 硬绑定仍是兜底首选
真正难处理的从来不是配置项本身,而是 DNS 污染 + IPv6 fallback + 项目级 repositories 覆盖这三者叠在一起——它们不会报错,只会让你反复重试、怀疑人生。动手前先跑两行 nslookup 和 curl -v,比翻文档快十倍。











