Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient request on networked docker container

I am new to docker containers and Im running into the following issue. I am developing a web page that makes requests to an exposed api. Both of them are published on different containers that are linked through a network. This is my docker-compose.yml file:

version: '2'

services:
  api:
    image: my/api
    networks:
      - api
    ports:
      - "8080:5000"    
    container_name: api  

  web:
    build:
      context: ./DockerWeb      
    networks:
      - api      
    ports:
      - "80:5000"    
    container_name: web

networks:    
  api:
    driver: bridge

I have noticed that if I attach to the container running my webpage I can ping the api container without any issue using ping api

The issue comes when trying to make any web service call to the api container. I am trying to initialize an HttpClient object, however the BaseAddress property of such an object must be set to a valid Uri.

_client = new HttpClient();
_client.BaseAddress = new Uri(config.ApiUrl); //config.ApiUrl = "api"

This throws the following error

UriFormatException: Invalid URI: The format of the URI could not be determined.

Is there a way to either a) Expose the container name in a different way, or b) make a call to a web service without the need of using a URI? How can I accomplish this?

UPDATE

I have updated the ApiUrl to contain the value http:api:8080, however now I am getting an exception when performing the call

System.AggregateException: One or more errors occurred. (An error occurred while sending the request.) ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.CurlException: Couldn't connect to server

I have also tried the calling the api endpoint directly from my web container using wget

wget http://api:8080/ 

However I still receive back an error:

Connecting to api (api)|172.24.0.4|:8080... failed: Connection refused

Could this be an API configuration error?

like image 975
luisgepeto Avatar asked Mar 20 '17 23:03

luisgepeto


1 Answers

api is just the hostname. The URI would be http://api:8080 (or https://api:someotherport if you set up SSL/TLS.)

like image 190
spender Avatar answered Sep 18 '22 12:09

spender