IPv6 导致网络卡顿
Ubuntu 24 上 composer install 特别慢,甚至要重试几次,服务器在法国,按道理不至于是这个速度。而且在服务器上调用第三方API的时候也经常出现:
Connection refused for URI https://xxx
先确认是不是 IPv6 导致
直接测试:
curl -4 https://repo.packagist.org/packages.json -I
curl -6 https://repo.packagist.org/packages.json -I
如果:
-4很快-6卡住 / timeout
那就是这个问题。我这就是 6 特别慢
强制 Ubuntu 优先 IPv4
编辑:
sudo nano /etc/gai.conf
取消这一行注释(如果没有就新增):
precedence ::ffff:0:0/96 100
然后保存。
然后重启服务:
sudo systemctl restart systemd-resolved
sudo systemctl restart systemd-networkd
然后清空 DNS 缓存:
sudo resolvectl flush-caches
再测:
ping packagist.org
看看能不能优先返回 IPv4。
# ping packagist.org PING packagist.org (79.127.134.129) 56(84) bytes of data. 64 bytes from unn-79-127-134-129.datapacket.com (79.127.134.129): icmp_seq=1 ttl=121 time=8.40 ms 64 bytes from unn-79-127-134-129.datapacket.com (79.127.134.129): icmp_seq=2 ttl=121 time=7.36 ms 64 bytes from unn-79-127-134-129.datapacket.com (79.127.134.129): icmp_seq=3 ttl=121 time=7.52 ms
我这边可以看到返回IPv4,TTL也很快,但要等很久(超过5秒)有开始有返回,还是很卡顿
执行 resolvectl status
# resolvectl status Global Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported resolv.conf mode: stub Link 2 (eth0) Current Scopes: DNS Protocols: +DefaultRoute -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported Current DNS Server: 213.136.95.11 DNS Servers: 213.136.95.10 213.136.95.11 2a02:c207::1:53
现在的 DNS 状态是:
DNS Servers:
213.136.95.10
213.136.95.11
2a02:c207::1:53 ← IPv6 DNS
关键点:
systemd-resolved 会同时尝试 IPv6 DNS
IPv6 实际不可用 / 路由很差
导致每次 DNS 查询先卡住(几秒)
然后才 fallback 到 IPv4
这就解释了:
| 现象 | 原因 |
|---|---|
| ping 5 秒才开始 | DNS 查询卡 IPv6 |
| curl -6 很慢 | IPv6 路由坏 |
| curl -4 很快 | IPv4 正常 |
| composer install 慢 | 每个域名解析都卡 |
解决方案:改 systemd-resolved
编辑:
sudo nano /etc/systemd/resolved.conf
改成这样:
[Resolve]
DNS=1.1.1.1 8.8.8.8
FallbackDNS=9.9.9.9
Domains=~.
DNSStubListener=yes
关键:不写任何 IPv6 DNS
然后执行:
sudo systemctl restart systemd-resolved
再测:
ping packagist.org
立马快了。