Mephisto_08
Mephisto_08

Reputation: 31

How to connect a Dockerized NATS client to a NATS server running in another Docker container?

I have two Docker containers, one running the NATS I/O server and the other acting as a client. Both containers are isolated from each other. I want the client to connect to the NATS server, but I'm unsure which address I should use to establish the connection.

The line causing confusion in my client code is:

s = natsConnection_ConnectTo(&conn, "nats://localhost:4222");

What address should I use to make the client successfully connect to the NATS server running in the separate Docker container?

Any help would be appreciated!

Upvotes: 1

Views: 1630

Answers (1)

b2f
b2f

Reputation: 349

Option 1

You can forward the port of the docker container running the server docker run -p 4222:4222 to the host and then access it via the client docker container through host.docker.internal by using docker run --add-host=host.docker.internal:host-gateway

https://medium.com/@TimvanBaarsen/how-to-connect-to-the-docker-host-from-inside-a-docker-container-112b4c71bc66

Option 2

Another option would be to create a network for the containers to share.

https://docs.docker.com/network/network-tutorial-standalone/

Option 3

An easy way to form a network is to pack them both into one docker compose file. Then you can access them by their respective service names.

https://docs.docker.com/compose/networking/

Upvotes: 0

Related Questions