Connecting to a Docker Container Outside of Docker Network

Connecting to a Docker Container Outside of Docker Network

When you run two or more services using docker-compose, it's normally not a problem for these services to talk to one another since they run on the same Docker network.

Usually, you just have to provide the service name instead of localhost.

For example, use:

http://server:4000

instead of:

http://localhost:4000

for the client to connect to the server.

Connecting to a Standalone Docker Container

However, when running these services individually using docker run, each container won't know the other container's service name, nor will localhost work.

The solution is to use host.docker.internal.

For example, use:

http://host.docker.internal:4000

instead of:

http://localhost:4000

Notes

  • Not sure if this works with Linux as well. Only tried it on macOS.
  • Sometimes, localhost works just fine (e.g., a non-Docker app connecting to a Dockerized app).