简体   繁体   English

如何在 docker compose 内的 Node.js 服务之间发送 json 消息

[英]How to send json messages between Node.js services inside a docker compose

Let's say I have two Node.js services running inside a docker compose.假设我有两个 Node.js 服务在 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)?服务 A 侦听端口 4000,服务 B 侦听端口 5000。如何将 json 消息从服务 A 发送到 B(反之亦然)(使用 Express)?

With a simple docker-compose file, the two services can access each other using their service name.通过一个简单的 docker-compose 文件,这两个服务可以使用它们的服务名称相互访问。 This is defined by the top level key underneath services: .这是由services:下面的顶级键定义的services: . In this simple example, service one could talk to service two by simply adressing it as http://two:5000 .在这个简单的例子中,服务one可以通过简单地将其寻址为http://two:5000来与服务two The other direction works the same using http://one:4000 assuming the processes internally listen on those port numbers.另一个方向使用http://one:4000工作相同,假设进程在内部侦听这些端口号。 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.确保不要在此处与本地主机(4444 和 5555)的端口映射混淆。

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 .有关更高级的设置,请参阅网络上的docker-compose 文档

I assume you are talking about REST APIs using JSON as data format.我假设您正在谈论使用 JSON 作为数据格式的 REST API。 There are many ways to do this.有很多方法可以做到这一点。 Express itself is used for building the server side, not the client. Express 本身用于构建服务器端,而不是客户端。 You can use the standard APIs like shown in the nodejs docs or one of several third party libraries to perform requests.您可以使用nodejs 文档中显示的标准 API 或多个第三方库之一来执行请求。 Axios for example is a pretty popular library for http requests.例如, Axios是一个非常流行的 http 请求库。 Seeone example for axios in the node docs , too.可以在节点文档中查看 axios 的一个示例

In most cases it's not a good idea to have circular connections using http requests in both directions.在大多数情况下,使用双向的 http 请求进行循环连接并不是一个好主意。 Maybe one of the two can act as the producing service and the other one is more like the consuming one?也许两者之一可以充当生产服务,而另一个更像是消费服务?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM