Search code examples
angulardockerdocker-composeangular2-services

Calling a service running in a docker container from an angular2 app


I have a UI application which is developed in Angular2. I also have a couple of services that are developed in Spring Boot. I am trying to call a Spring Boot service from the Angular application.

Below is my docker-compose.yml

version: '2'
networks:
  mynet:
services:
  ui:
    image: uiimg
    networks:
      - mynet
    ports:
      - "4200:4200"
  srvc:
    image: scservice
    networks:
      - mynet
    ports:
      - "8080:8080"
  testsrvc:
    image: testsrvc
    networks:
      - mynet
    ports:
      - "8081:8081"      

This is how I am calling the service defined by "srvc" from angular.

return this.http.get("http://srvc:8080/test").map(result => result.json());

But I am getting the error srvc:8080/test Failed to load resource: net::ERR_NAME_NOT_RESOLVED

However, I can call http://srvc:8080/test from another service in "testsrvc" without any issues.

My understanding is that since the UI request originates from the browser, it has no means of knowing what "srvc" is, whereas since "testsrvc" also runs in a container, it can link to "srvc"

So how should I be calling "srvc" from angular?

P.S: I tried http://srvc:8080/test and http://srvc/test Neither is working.

The angular application in the container is up and running and I am able to access it from http://localhost:4200


Solution

  • The angular application in the container is up and running and I am able to access it from http://localhost:4200

    this is the correct way of accessing the container from your host machine.

    if you wanted to use http://srvc:8000, you would have to be inside of a Docker container in the same Docker network. your docker-compose configuration has this set up correctly, so you could access that network name and port from within one of your other docker containers.

    but from your host machine, you don't have access to the network names of the containers. mapping the port allows you to access the service in the container through localhost, as you are seeing.

    your other option, if you need your host to be able to see srvc as a proper name, is to edit your hosts file and add an entry for that. just map srvc to 127.0.0.1 and then you will be able to use http://srvc:8000 from your host machine, and it will route to localhost:8000.