skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    location /api/ {
        proxy_pass http://main:3000/;
    }
    

    doing request to the address /api/ will forward all the requests to the backend so /api/users will end up as http://main:3000/users and so the ip is resolved by docker and because the request goes through the server, there is no CORS issue.


  2. How can I get the ip address I must send the requests to

    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

    1. A network called myapp_default is created.
    2. A container is created using web’s configuration. It joins the network myapp_default under the name web.
    3. A container is created using db’s configuration. It joins the network myapp_default under the name db.

    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.

    version: "3.9"
    services:
      web:
        build: .
        ports:
          - "8000:8000"
      db:
        image: postgres
        ports:
          - "8001:5432"
    

    You can get more details here

    CORS you can configure in your API header

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search