TheWebGuy
TheWebGuy

Reputation: 12525

Docker web app can't communicate with API app

I have 2 .net core apps running in docker (one is a web api, the other is a web app consuming the web api):

I can't seem to communicate with the api via the web app, but I can access the api by going directly to it in my browser at http://localhost:44389

I have an environment variable in my web app that has that same info, but it can't get to it.

If I were to specify the deployed version of my API on azure, it's able to communicate with that address. Seems like the problem is the containers talking to each other.

I read that creating a bridge should fix that problem but it doesn't seem to. What am I doing wrong?

Here is my docker compose file:

version: '3.4'

services:
  rc.api:
    image: ${DOCKER_REGISTRY}rcapi
    build:
      context: .
      dockerfile: rc.Api/Dockerfile
    ports:
      - "44389:80"

  rc.web:
    image: ${DOCKER_REGISTRY}rcweb
    build:
      context: .
      dockerfile: rc.Web/Dockerfile
    environment:
      - api_endpoint=http://localhost:44389
    depends_on:
      - rc.api

networks:
  my-net:
    driver: bridge

Upvotes: 1

Views: 910

Answers (2)

Gor Kotikyan
Gor Kotikyan

Reputation: 723

docker-compose automatically creates a network between your containers. As your containers are in the same network you would be able to connect between containers using aliases. docker-compose creates an alias with the container name and the container IP. So in your case docker-compose should look like

version: '3.4'

services:
  rc.api:
    image: ${DOCKER_REGISTRY}rcapi
    build:
      context: .
      dockerfile: rc.Api/Dockerfile
    ports:
      - "44389:80"

  rc.web:
    image: ${DOCKER_REGISTRY}rcweb
    build:
      context: .
      dockerfile: rc.Web/Dockerfile
    environment:
      - api_endpoint=http://rc.api
    depends_on:
      - rc.api

networks:
  my-net:
    driver: bridge

As in rc.api opens port 80 in its container, therefore rc.web can access to 80 port with http://rc.api:80 or http://rc.api (without port since HTTP port is default 80)

Upvotes: 5

Alexander Zeitler
Alexander Zeitler

Reputation: 13089

You need to call http://rc.api because you have two containers and the API containers localhost is different from the web apps container localhost.

The convention is each service can be resolved by its name specified in the docker-compose.yml.

Thus you can call the API on internal Port 80 instead of exposing it on a particular port.

Upvotes: 0

Related Questions