I’m setting up a little web project with docker-compose. the front is a VueJS served by a nginx server in the container named frontend, and the back is a NestJS in the container named main. Both are run with a docker-compose.yml
file, both are in the same network, and both can reach each other (a curl http://main:3000
from the frontend container works).
This is all good until I start working on the JS in my Vue to make backend requests. I’m trying to reach the container (a GET request on my NestJS) but the question is: How do I do this ? Because the request in itself doesn’t come from inside the container but my browser, so I can’t find a way to reach the container.
First problem: How can I get the ip address I must send the requests to (the address of the main
container)
Second problem: How do I avoid the CORS issue of my browser blocking my requests ?
Those questions may seem easy for people who may know docker, nginx or JS but I admit not really understanding nginx and Docker very well so even links to documentation may help.
Notes:
The nginx of my frontend container uses the default nginx.conf
for I don’t know what can I change to make it work.
The backend is served by an nginx but if it can solve the problem I’ll gladly do so
2
Answers
As Sirko pointed out in the comments, the easiest way to solve this problem it to use a reverse proxy. By setting a reverse proxy such as:
doing request to the address
/api/
will forward all the requests to the backend so/api/users
will end up ashttp://main:3000/users
and so the ip is resolved by docker and because the request goes through the server, there is no CORS issue.To answer this question, you can discover services by their name you do not need ip address and you should not use ip address as those are volatile
So if you have docker-compone.yaml like below in a directory called myapp, then
Each container can now look up the hostname web or db and get back the appropriate container’s IP address. For example, web’s application code could connect to the URL postgres://db:5432 and start using the Postgres database.
You can get more details here
CORS you can configure in your API header