在VM中搭建Go HTTP服务器时curl localhost:8080遇DNS错误如何解决?
解决Go HTTP服务器localhost DNS解析失败问题
先明确测试场景,对应不同解决方案:
场景1:在虚拟机内部执行curl测试
- 直接绕开DNS解析测试:执行
curl 127.0.0.1:8080,如果能正常返回内容,说明是localhost的DNS映射问题。 - 修复localhost映射:检查系统hosts文件:
- Linux/macOS:编辑
/etc/hosts,确保存在以下两行:127.0.0.1 localhost ::1 localhost - Windows:以管理员身份编辑
C:\Windows\System32\drivers\etc\hosts,添加上述两行。
- Linux/macOS:编辑
- 刷新DNS缓存:
- Linux:执行
systemctl restart systemd-resolved(不同发行版可能有差异,CentOS可尝试service named restart) - Windows:执行
ipconfig /flushdns - macOS:执行
dscacheutil -flushcache
- Linux:执行
场景2:在宿主机(虚拟机外部)执行curl测试
- 使用虚拟机实际IP访问:localhost是宿主机的回环地址,无法指向虚拟机。先在虚拟机里执行
ip addr(Linux)或ipconfig(Windows)获取虚拟机的网卡IP(比如192.168.1.100),然后在宿主机执行curl 192.168.1.100:8080。 - 开放虚拟机端口防火墙:如果还是无法访问,检查虚拟机的防火墙是否允许8080端口:
- Linux:执行
ufw allow 8080(使用ufw防火墙时),或者iptables -A INPUT -p tcp --dport 8080 -j ACCEPT - Windows:在防火墙高级设置里添加8080端口的入站规则
- Linux:执行
关于你的Go代码说明
你的代码里http.ListenAndServe(":8080", nil)是正确的,这个配置会让服务监听虚拟机的所有网络接口,不管是回环地址还是网卡IP,所以不需要修改代码。
内容的提问来源于stack exchange,提问作者user19899551
相关产品推荐
相关产品推荐

