Call to API from Angular in Nginx does not resolve Docker service name

南楼画角 提交于 2021-01-29 05:30:15

问题


I have an Angular app running in a NginX Docker container.

The Angular app can make a REST call to another container (Spring Boot API Docker) using localhost as server.

server: string = 'localhost';
return this.httpClient.post<MyClass[]>('http://' + this.server + ':6060/files-data/list-files', request);

But REST call fails when using Docker service name instead.

server: string = 'files-service';
return this.httpClient.post<MyClass[]>('http://' + this.server + ':8080/files-data/list-files', request);

*using 8080 port this time as trying to resolve docker service name

Error in UI console:

net::ERR_NAME_NOT_RESOLVED

Using default NginXimage with default nginx.conf.

  nginx-files-ui:
    image: nginx:latest
    container_name: nginx-files-ui
    volumes:
      - ./files-ui/dist/html:/usr/share/nginx/html
    ports:
      - 99:80

Containers all run on same Docker network.

networks:
  default:
    external:
      name: files-net

Modified nginx.conf to include resolver but no joy.

resolver 127.0.0.11 valid=30s;

Any idea why I cannot make a REST call using Docker service name ?

EDIT

It seems Angular code running in browser is not able to resolve service names.

Docker composed services can't communicate by service name


回答1:


I think this is the very common misunderstanding when running application inside docker container, especially for browser apps :).

You can only call API using service name in your app if your app and the api are running and being accessed within same network. In your case, the Angular app and your backend are running in same network,but the Angular app is being accessed from host machine, not inside container.

Detail: In current context, when you access your Angular app from browser, you're using the Angular app in host machine, in host network, not inside container anymore, your Angular app is exposed by mapping port from container to host machine. Therefore when you make an API request, it'll coming from host machine -> docker container, at that time, host machine will try to resolve service name in current context and of course from host machine there's no service name

Therefore, for all browser apps, even you deploy it using docker container, but when you call API, mostly you'll have to use localhost:<mapped_port> or something that resolve to host machine not inside docker container (Eg: domain name).



来源:https://stackoverflow.com/questions/65766633/call-to-api-from-angular-in-nginx-does-not-resolve-docker-service-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!