Home > front end >  How do I connect two containers on MacOS without using service name
How do I connect two containers on MacOS without using service name

Time:02-26

I am running two docker services which is not authored by me, that needs to communicate with each other. The first container expects to communicate with the other service via a specific port number, lets say via port 8008.

When i run the two containers on a Linux machines, container A can easily reach container B via port 8008.

But when I try to run on my mac, the container A cannot reach container B via port 8008. It fails with following error:

FetchError: request to http://127.0.0.1:8008/ failed, reason: connect ECONNREFUSED 127.0.0.1:8008

I found this StackOverflow question here which provides a way for two containers to communicate on a mac, the only problem is that the solution requires setting up a service name, and use this to access the other container (together with making sure they are on the same network)

This cannot work for me, as I do not have control of the way the container A communicates with container B. Container A expects the service provided by container B to be reachable via 127.0.0.1.

Is there a way I can set this up? And have two containers on a MAC communicate with each other using localhost/127.0.0.1?

CodePudding user response:

When you create a container, it is possible to assign it the network stack of another container. This allows the two containers to communicate via the loopback interface (localhost, that is). Though I'm not sure if it works on Mac. Try with the commands below.

Start an NGINX container that will listen on port 80:

docker run --rm --name tmp-nginx nginx

Open another terminal and start a container with curl, giving it the network of the tmp-nginx container:

docker run --rm --net=container:tmp-nginx curlimages/curl http://localhost:80

If everything went well, you'll see this:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
[the rest is truncated]

If that worked, then you can use the same trick with your services. Simply start one of them with the extra flag:

--net=container:[INSERT NAME OF THE OTHER CONTAINER]
  • Related