Search code examples
dockermacos

Connecting from a docker container to the host on MacOS


I am trying co connect from a container to a server running on the host running MacOS. The server runs on port 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}`); });

And it works:

❯ 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)

I run a container, install curl and try to access the host:

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

So: the host host.docker.internal is pingable. But the connection is refused.

I guess it has something to do with my MacOS. Any ideas?


Solution

  • Your server needs to be listening on all network interfaces :

    const host = '0.0.0.0'; const port = 8002;