Let's first start by verifying the usage of our Node.js app but without a proxy. Create a folder called my app and go into it. Next, create an index.js file with some contents. This is a simple Node.js script that responds "welcome to Node.js" on every request. Note that we are listening for requests on port 3000.
Let's start our Node.js app and keep it running in the background using noop. Check to make sure Node.js is running by typing curl local host 3000. Seeing the "welcome to Node.js" output tells us that our Node.js app is properly running.
Let's now set up our NGINX proxy. First, start NGINX. Check to make sure NGINX is running by typing curl local host and confirm that you see the "welcome to NGINX" HTML output. We will need to set up our custom NGINX configuration in order to proxy web request to our Node.js app.
First, let's blank out any configuration that's already there for the default site. Then open up the file for editing. We'll start by adding a server directive. By default, NGINX will listen on port 80 with a blank server name. Next, let's add a location block. Use the front slash to match this configuration to all URLs in this server.
Let's add some directives to the location block, starting with the proxy set header directives. These are fields we want to pass to our Node.js app. Let's be sure to pass the host name to Node. Let's also send some extra headers to pass over the visitor's IP address. We also want to pass over the protocol used, either HTTP or HTTPS.
The proxy_pass directive is where all the magic happens. This tells NGINX where to proxy request to. We'll use local host 3000, the URL of our Node.js app. This is now enough to proxy request.
Note that we didn't set any other directives that truly aren't needed as NGINX will just use the default settings if they are not already defined.In production apps, you may want to add or define other directives based on your needs.
Save the file and reload NGINX. Let's check the response from local host again. This time instead of seeing the default NGINX page, we are seeing output from our Node.js app which tells us that NGINX is properly proxying requests to Node.js.