解决 Homebrew 报错 Could not resolve host: github.com 网络阻断
在 macOS 上执行 brew update 或 brew install 时提示 Fatal: unable to access ... Could not resolve host: github.com。本文详解 DNS 污染解析、Git 代理配置及切换为国内官方镜像源的完整解决方案。
问题现象
在 macOS 终端执行 brew update、brew upgrade 或安装软件包时,更新流程卡死随后报错退出:
Updating Homebrew...
fatal: unable to access 'https://github.com/Homebrew/brew/': Could not resolve host: github.com
Error: Fetching /opt/homebrew failed!
任何依赖 Homebrew Core 与 Cask 的软件拉取均不可用。
触发根因
- DNS 域名解析失败或受到污染:本地使用的运营商 DNS 无法稳定解析
github.com的 IP 地址,或返回了无效解析。 - Git 客户端配置了失效的 HTTP 代理:之前配置过科学上网工具(如 127.0.0.1:7890),但在代理客户端关闭后,Git 全局配置文件
~/.gitconfig中依然保留了代理设置,导致流量被强行转发至不存在的本地端口。 - 跨国链路网络波动与防重放超时。
诊断排查步骤
1. 验证基础 DNS 解析与连通性
nslookup github.com
curl -I https://github.com
若 nslookup 提示 server can't find github.com: NXDOMAIN 或超时,说明是纯 DNS 问题。
2. 检查 Git 是否配置了残留代理
git config --global --get http.proxy
git config --global --get https.proxy
如果返回了 http://127.0.0.1:xxxx,说明存在代理阻断。
解决方案
方案一:清理失效的 Git 全局代理设置
如果当前未开启代理软件:
git config --global --unset http.proxy
git config --global --unset https.proxy
如果正在使用代理工具,确保为 Homebrew 环境变量提供正确的代理地址:
export ALL_PROXY=socks5://127.0.0.1:7890
export http_proxy=http://127.0.0.1:7890
export https_proxy=http://127.0.0.1:7890
方案二:配置优质公共 DNS 服务器
前往 macOS 系统设置 -> 网络 -> 高级 -> DNS,添加公共抗污染 DNS:
223.5.5.5(阿里公共 DNS)119.29.29.29(腾讯公共 DNS)8.8.8.8(Google Public DNS)
刷新本地 DNS 缓存:
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder
方案三:切换 Homebrew 为国内高校镜像源(最彻底稳定)
将 Homebrew 的软件仓库上游替换为清华大学或中科大镜像源:
# 替换 brew.git:
git -C "$(brew --repo)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git
# 替换 homebrew-core.git:
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git
# 替换 homebrew-cask.git:
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git
# 注入环境变量至 ~/.zshrc 或 ~/.bash_profile
echo 'export HOMEBREW_API_DOMAIN="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles/api"' >> ~/.zshrc
echo 'export HOMEBREW_BOTTLE_DOMAIN="https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles"' >> ~/.zshrc
source ~/.zshrc
验证方法
执行更新与安装测试:
brew update
brew --version
输出显示:
Already up-to-date.
Homebrew 4.x.x
更新秒级完成无任何网络阻断提示,修复完毕。


