You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacOS下Docker容器无法连接主机8002端口问题求助

问题:Docker容器无法连接MacOS主机上的8002端口服务

我在MacOS主机上运行了一个Node.js HTTP服务器,监听8002端口,但从Alpine Docker容器中无法通过host.docker.internal访问该服务——ping能通目标地址,但curl连接被拒绝。

服务器代码

var http = require("http");
 
const host = 'localhost'; const port = 8002;
 
const requestListener = function (req, res) {
    res.writeHead(200);
    res.end("My first server!"); 
};
 
const server = http.createServer(requestListener); 
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`); 
});

主机监听状态(lsof输出)

❯ lsof -NP -iTCP -sTCP:LISTEN

COMMAND     PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
[..]
node      39917  user   17u  IPv6 0x10940b81a82e2f84      0t0  TCP localhost:8002 (LISTEN)

容器内操作记录

docker run --rm -it alpine sh
# apk add curl

# ping host.docker.internal
PING host.docker.internal (192.168.65.254): 56 data bytes
64 bytes from 192.168.65.254: seq=0 ttl=63 time=0.639 ms

# curl http://host.docker.internal:8002
curl: (7) Failed to connect to host.docker.internal port 8002 after 3 ms: Couldn't connect to server

解决思路

  • 问题核心:当前服务器仅绑定到localhost(对应IPv6的::1地址),而Docker容器通过host.docker.internal访问的是主机的IPv4地址(192.168.65.254),服务没有监听该IPv4接口,导致连接被拒绝。

方案1:修改服务器监听所有网络接口

将Node.js代码中的host变量改为0.0.0.0,这样服务会监听主机上所有可用的网络接口(包括IPv4和IPv6):

var http = require("http");
 
const host = '0.0.0.0'; // 改为监听所有接口
const port = 8002;
 
const requestListener = function (req, res) {
    res.writeHead(200);
    res.end("My first server!"); 
};
 
const server = http.createServer(requestListener); 
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`); 
});

重启服务器后,用lsof检查会看到服务监听*:8002,此时容器即可通过http://host.docker.internal:8002正常访问。

方案2:绑定到主机的IPv4地址

如果不想监听所有接口,可以将host设置为主机的实际IPv4地址(比如192.168.65.254,可通过ifconfig或ipconfig查询),让服务仅监听该特定地址,容器同样能通过host.docker.internal访问。

验证步骤

修改后重启服务器,执行lsof -NP -iTCP -sTCP:LISTEN,确认输出中出现TCP *:8002 (LISTEN)或TCP [你的IPv4地址]:8002 (LISTEN)的条目,再进入容器执行curl http://host.docker.internal:8002,即可正常获取响应内容。


内容的提问来源于stack exchange,提问作者Pepe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:52:42