简体   繁体   中英

docker-compose: service-to-service communication not working as expected

I have made api which collects data from multiple sources(they do post requests on 88 and 99 posrts in this examples) and then provides aggregate of this data through few endpoints. Then I have two apps that get data from this api and do visualisation. I have pinpointed this issue: although docker-compose docunentation(any many tutorials) clearly states:

It is important to note the distinction between HOST_PORT and CONTAINER_PORT. In the above example, for db, the HOST_PORT is 8001 and the container port is 5432 (postgres default). Networked service-to-service communication use the CONTAINER_PORT. When HOST_PORT is defined, the service is accessible outside the swarm as well.

... but my 2 apps still can't reach api.

If I expose my api port on both apps I get error that this port is already given(as expected per docs), but what I can't understand is why these apps can't call api without exposing ports(isn't it service-to-service communication?). I also found multiple same solutions with nginx , but because it's my own free person project I'd like to learn where I'm wrong and do it the right way, because obviously I misunderstand something from documentation. My goal right now is only for my two apps to be able to do api call. For now it's on single hostCould please anyone help with solution or tips and ideas?

My current docker-compose

services:
  host:
    image: "api_host"
    ports:
      - 88:88
      - 99:99
  app1:
    image: "app"
    ports:
      - 7777:7777
  app2:
    image: "app"
    ports:
      - 8888:8888```

The issue is that while your compose file brings up 3 containers, these containers are not networked together. To fix this define a network for them in the compose file. This will ensure that your host and API can communicate with each-other on the specified ports. It will also allow you to call the API and hosts based on the service name (ie in a configuration file).

Example Compose with Network:

services:
  host:
    image: "api_host"
    ports:
      - 88:88
      - 99:99
    networks:
      - myapinetwork
  app1:
    image: "app"
    ports:
      - 7777:7777
    networks:
      - myapinetwork
  app2:
    image: "app"
    ports:
      - 8888:8888```

networks:
    myapinetwork:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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