Issue
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 NginX
image 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
Solution
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 resolves to host machine not inside docker container (Eg: domain name).
Answered By - Duc Trung Mai
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.