我正在尝试从容器连接到运行 MacOS 的主机上运行的服务器。 服务器运行在8002端口
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 -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)
我运行一个容器,安装curl并尝试访问主机:
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
因此:主机 host.docker.internal 是可 ping 通的。 但连接被拒绝。
我猜这和我的MacOS有关。 有什么想法吗?
您的服务器需要侦听所有网络接口:
const host = '0.0.0.0'; const port = 8002;