Setup an Nginx Proxy for a Node.js App

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 6 years ago

Learn how to setup an Nginx proxy server that sits in front of a Node.js app. You can use a proxy to control the flow of frontend requests hitting your app, as well as to achieve better performance and scalability. We'll create a sample Node.js app and configure a default Nginx configuration file to proxy web requests.

[00:00] 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.

[00:23] 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.

[00:40] 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.

[01:00] 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.

[01:22] 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.

[01:48] 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.

[02:03] 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.

[02:14] 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.