“Could not connect”错误通常由DNS解析失败引发。需依次检查nslookup解析结果、/etc/resolv.conf配置、systemd-resolved状态,并在容器等受限环境中确认DNS注入是否有效。

如果您执行 apt-get update 命令时收到 “Could not connect” 错误,该提示通常不直接指向 DNS 配置丢失,但很可能是由 DNS 解析失败引发的底层连通性中断。以下是排查与修复此问题的多种路径:
一、验证 DNS 解析是否正常
该步骤用于确认系统能否将软件源域名(如 archive.ubuntu.com)正确转换为 IP 地址。若解析失败,后续所有连接尝试均会因目标地址未知而报“Could not connect”。
1、在终端中运行:nslookup archive.ubuntu.com
2、观察输出:若返回 server can't find archive.ubuntu.com: NXDOMAIN 或 connection timed out; no servers could be reached,则表明 DNS 配置异常或上游 DNS 服务不可用。
3、检查当前 DNS 配置文件内容:cat /etc/resolv.conf
二、临时覆盖 DNS 配置进行测试
该方法绕过现有配置,使用已知可靠的公共 DNS 服务器发起解析请求,可快速判断是否为 DNS 设置导致的问题。
1、执行命令临时指定 DNS:nslookup archive.ubuntu.com 8.8.8.8
2、若该命令返回有效 IP,则说明本地 /etc/resolv.conf 中的 nameserver 条目失效或配置错误。
3、可进一步用该 DNS 运行更新测试:sudo apt-get -o Acquire::http::Proxy=false -o Acquire::https::Proxy=false update
三、重写 /etc/resolv.conf 文件
该操作将强制替换当前 DNS 设置,适用于 resolv.conf 被清空、写入非法地址或被只读挂载锁定的场景。
1、备份原文件:sudo cp /etc/resolv.conf /etc/resolv.conf.bak
2、清空并写入可信 DNS:echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf && echo "nameserver 1.1.1.1" | sudo tee -a /etc/resolv.conf
3、确认写入成功:sudo cat /etc/resolv.conf
四、检查 systemd-resolved 是否干扰
在启用 systemd-resolved 的 Ubuntu 系统中,/etc/resolv.conf 可能是符号链接,实际 DNS 由 resolved 管理;若其服务异常,会导致全局解析失败。
1、检查链接状态:ls -l /etc/resolv.conf
2、若指向 /run/systemd/resolve/stub-resolv.conf 或 /run/systemd/resolve/resolv.conf,运行:sudo systemctl status systemd-resolved
3、若状态为 inactive 或 failed,重启服务:sudo systemctl restart systemd-resolved
五、排除容器或受限环境中的 DNS 隔离
在 Docker 容器、chroot 环境或 Kubernetes Pod 中,/etc/resolv.conf 可能被宿主机注入或覆盖,但未包含有效 nameserver,导致 apt 无法解析任何域名。
1、检查容器内 resolv.conf 是否为空或仅含 127.0.0.11(Docker 默认 DNS)且无对应服务。
2、启动容器时显式指定 DNS:docker run --dns 8.8.8.8 --dns 114.114.114.114 -it ubuntu:22.04 apt-get update
3、若在 Kubernetes 中,检查 Pod 的 dnsPolicy 字段是否为 Default 或 ClusterFirst,并确认 CoreDNS Pod 正常运行。











