Let’s say I have two Node.js services running inside a docker compose. Service A listens to port 4000 and service B listens to port 5000. How can I send a json message from service A to B (and vice versa) (by using Express)?
Advertisement
Answer
With a simple docker-compose file, the two services can access each other using their service name. This is defined by the top level key underneath services:
. In this simple example, service one
could talk to service two
by simply adressing it as http://two:5000
. The other direction works the same using http://one:4000
assuming the processes internally listen on those port numbers. Both containers could also listen on the same port internally as they have different network interfaces. Make sure to not get confused with the port mappings to your localhost (4444 and 5555) here.
version: "3.8" services: one: image: yourname/yourimage-one ports: - "4444:4000" two: image: yourname/yourimage-two ports: - "5555:5000"
For more advanced setups, please refer to the docker-compose docs on networking.
I assume you are talking about REST APIs using JSON as data format. There are many ways to do this. Express itself is used for building the server side, not the client. You can use the standard APIs like shown in the nodejs docs or one of several third party libraries to perform requests. Axios for example is a pretty popular library for http requests. See one example for axios in the node docs, too.
In most cases it’s not a good idea to have circular connections using http requests in both directions. Maybe one of the two can act as the producing service and the other one is more like the consuming one?