Nginx with Frontend and Backend Server

Viewed 13

I'm working on a CTF that will be downloaded and run locally on a VM. The IP address of the CTF will be different for each user. I have a frontend server (React.js) running on port 3000. I'm making a request like so to the backend server:

fetch("http://localhost:5000/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })

The backend server (express.js) is running on port 5000. I have nginx configured to route port 3000 request to port 80.

listen 80 default_server;
listen [::]:80 default_server;

location / {
      proxy_pass http://localhost:3000; 
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
}

When the CTF is booted a user will get a private IP like so: 192.168.2.136. My question is, how do I make request to the backend because fetch("http://localhost:5000/login) will not fetch from the backend. I will need to do fetch("http://192.168.2.136:5000/login for it to work. Can this issue be resolved with nginx, or will I need to look into a way to get the private IP address when the VM boots?

1 Answers

For anyone with the same issue, I fixed it by using a server name in nginx and properly routing the backend traffic to my backend server like so:

server {
        listen 80;

        server_name resume.tm;

        location / {
                proxy_pass http://localhost:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
        }

        location /api/ {
                proxy_pass http://localhost:5000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
        }
}
Related