Search code examples
dockernginxreverse-proxy

How can I reverse proxy my API requests with nginx?


To add some context:

I'm running an Angular PWA with Node.js backend. They run on different ports:

· Front-end: Hosted by nginx on port 80

· Back-end: Hosted by Node.js on port 3939

nginx is within a Docker container.


Thing is, I plan to redirect all traffic related to /api from port 80 to port 3939 internally via reverse proxy. I'm testing with /api/agenda to see if it works, but it isn't.

Here's the default.conf file I'm using:

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /api/agenda {
                proxy_pass   http://localhost:3939;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

I'm testing with Postman to see if redirect works, but I'm getting a 404 while accessing with this url: http://localhost:80/api/agenda

If I access it using its original port, I do get the desired results, but that's not what I want to do. http://localhost:3939/api/agenda


Edit: Here's the error logs I get in my docker console when I try to access http://localhost:80/api/agenda

1 | 172.19.0.1 - - [22/Jun/2022:07:13:50 +0000] "GET /api/agenda HTTP/1.1" 404 555 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36" "-"

nginx-conf-web-1 | 2022/06/22 07:55:18 [error] 28#28: *8 connect() failed (111: Connection refused) while connecting to upstream, client: 172.19.0.1, server: localhost, request: "GET /api/agenda HTTP/1.1", upstream: "http://127.0.0.1:3939/api/agenda", host: "localhost:80"

Thanks in advance for your help.


Solution

  • One of the comments worked for me, regarding @Ivan Shatsky.

    Switching: "https://localhost:port/api to: https://host.docker.internal:port/api

    Thank you to the people in the comments.