Tutorial

How To Set Up a Node.js Application for Production on Ubuntu 16.04

How To Set Up a Node.js Application for Production on Ubuntu 16.04
Not using Ubuntu 16.04?Choose a different version or distribution.
Ubuntu 16.04

Introduction

Node.js is an open-source JavaScript runtime environment for building server-side and networking applications. The platform runs on Linux, MacOS, FreeBSD, and Windows. Node.js applications can be run at the command line, but we’ll focus on running them as a service, so that they will automatically restart on reboot or failure, and can safely be used in a production environment.

In this tutorial, we will cover setting up a production-ready Node.js environment on a single Ubuntu 16.04 server. This server will run a Node.js application managed by PM2, and provide users with secure access to the application through an Nginx reverse proxy. The Nginx server will offer HTTPS, using a free certificate provided by Let’s Encrypt.

Prerequisites

This guide assumes that you have the following:

When you’ve completed the prerequisites you will have a server serving the default Nginx placeholder page at https://example.com/.

Let’s get started by installing the Node.js runtime on your server.

Step 1 — Installing Node.js

We will install the latest LTS release of Node.js, using the NodeSource package archives.

First, you need to install the NodeSource PPA in order to get access to its contents. Make sure you’re in your home directory, and use curl to retrieve the installation script for the Node.js 16.x archives:

  1. cd ~
  2. curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh

You can inspect the contents of this script with nano (or your preferred text editor):

  1. nano nodesource_setup.sh

Then run the script under sudo:

  1. sudo bash nodesource_setup.sh

The PPA will be added to your configuration and your local package cache will be updated automatically. After running the setup script from nodesource, you can install the Node.js package in the same way that you did above:

  1. sudo apt-get install nodejs

The nodejs package contains the node binary as well as npm, so you don’t need to install npm separately. However, in order for some npm packages to work (such as those that require compiling code from source), you will need to install the build-essential package:

  1. sudo apt-get install build-essential

The Node.js runtime is now installed, and ready to run an application. Let’s write a Node.js application.

Step 2 — Creating a Node.js Application

We will write a Hello World application that returns “Hello World” to any HTTP requests. This is a sample application that will help you get your Node.js set up, which you can replace with your own application — just make sure that you modify your application to listen on the appropriate IP addresses and ports.

Hello World Code

First, create and open your Node.js application for editing. For this tutorial, we will use nano to edit a sample application called hello.js:

  1. cd ~
  2. nano hello.js

Insert the following code into the file. If you want to, you may replace the highlighted port, 8080, in both locations (be sure to use a non-admin port, i.e. 1024 or greater):

hello.js
#!/usr/bin/env nodejs
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080, 'localhost');
console.log('Server running at http://localhost:8080/');

Now save and exit.

This Node.js application listens on the specified address (localhost) and port (8080), and returns “Hello World” with a 200 HTTP success code. Since we’re listening on localhost, remote clients won’t be able to connect to our application.

Test Application

In order to test your application, set hello.js to be executable using chmod:

  1. chmod +x ./hello.js

Then run it like so:

  1. ./hello.js
Output
Server running at http://localhost:8080/

Note: Running a Node.js application in this manner will block additional commands until the application is killed by pressing Ctrl-C.

In order to test the application, open another terminal session on your server, and connect to localhost with curl:

  1. curl http://localhost:8080

If you see the following output, the application is working properly and listening on the proper address and port:

Output
Hello World

If you do not see the proper output, make sure that your Node.js application is running, and configured to listen on the proper address and port.

Once you’re sure it’s working, switch back to your other terminal and kill the Node.js application (if you haven’t already) by pressing Ctrl+C.

Step 3 — Installing PM2

Now we will install PM2, which is a process manager for Node.js applications. PM2 provides an easy way to manage and daemonize applications (run them in the background as a service).

We will use npm, a package manager for Node modules that installs with Node.js, to install PM2 on our server. Use this command to install PM2:

  1. sudo npm install -g pm2

The -g option tells npm to install the module globally, so that it’s available system-wide.

Step 4 — Managing Applications with PM2

We will cover a few basic uses of PM2.

Start Application

The first thing you will want to do is use the pm2 start command to run your application, hello.js, in the background:

  1. pm2 start hello.js

This also adds your application to PM2’s process list, which is outputted every time you start an application:

Output
[PM2] Spawning PM2 daemon with pm2_home=/home/sammy/.pm2 [PM2] PM2 Successfully daemonized [PM2] Starting /home/sammy/hello.js in fork_mode (1 instance) [PM2] Done. ┌─────┬──────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐ │ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │ ├─────┼──────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤ │ 0 │ hello │ default │ N/A │ fork │ 13734 │ 0s │ 0 │ online │ 0% │ 25.0mb │ sammy │ disabled │ └─────┴──────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

As you can see, PM2 automatically assigns a name (based on the filename, without the .js extension) and a PM2 id. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

Applications that are running under PM2 will be restarted automatically if the application crashes or is killed, but an additional step needs to be taken to get the application to launch on system startup (boot or reboot). Luckily, PM2 provides an easy way to do this, the startup subcommand.

The startup subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots:

  1. pm2 startup systemd

The last line of the resulting output will include a command that you must run with superuser privileges:

Output
[PM2] Init System found: systemd [PM2] You have to run this command as root. Execute the following command: sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u sammy --hp /home/sammy

Run the command that was generated (similar to the highlighted output above, but with your username instead of sammy) to set PM2 up to start on boot (use the command from your own output):

  1. sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u sammy --hp /home/sammy

This will create a systemd unit which runs pm2 for your user on boot. This pm2 instance, in turn, runs hello.js. You can check the status of the systemd unit with systemctl:

  1. systemctl status pm2-sammy

For a detailed overview of systemd, see Systemd Essentials: Working with Services, Units, and the Journal.

Other PM2 Usage (Optional)

PM2 provides many subcommands that allow you to manage or look up information about your applications. Note that running pm2 without any arguments will display a help page, including example usage, that covers PM2 usage in more detail than this section of the tutorial.

Stop an application with this command (specify the PM2 App name or id):

  1. pm2 stop app_name_or_id

Restart an application with this command (specify the PM2 App name or id):

  1. pm2 restart app_name_or_id

The list of applications currently managed by PM2 can also be looked up with the list subcommand:

  1. pm2 list

More information about a specific application can be found by using the info subcommand (specify the PM2 App name or id):

  1. pm2 info example

The PM2 process monitor can be pulled up with the monit subcommand. This displays the application status, CPU, and memory usage:

  1. pm2 monit

Now that your Node.js application is running, and managed by PM2, let’s set up the reverse proxy.

Step 5 — Setting Up Nginx as a Reverse Proxy Server

Now that your application is running, and listening on localhost, you need to set up a way for your users to access it. We will set up the Nginx web server as a reverse proxy for this purpose.

In the prerequisite tutorial, we set up our Nginx configuration in the /etc/nginx/sites-available/default file. Open the file for editing:

  1. sudo nano /etc/nginx/sites-available/default

Within the server block you should have an existing location / block. Replace the contents of that block with the following configuration. If your application is set to listen on a different port, update the highlighted portion to the correct port number.

/etc/nginx/sites-available/default
. . .
    location / {
        proxy_pass http://localhost:8080;
        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;
    }
}

This configures the server to respond to requests at its root. Assuming our server is available at example.com, accessing https://example.com/ via a web browser would send the request to hello.js, listening on port 8080 at localhost.

You can add additional location blocks to the same server block to provide access to other applications on the same server. For example, if you were also running another Node.js application on port 8081, you could add this location block to allow access to it via http://example.com/app2:

/etc/nginx/sites-available/default — Optional
    location /app2 {
        proxy_pass http://localhost:8081;
        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;
    }

Once you are done adding the location blocks for your applications, save and exit.

Make sure you didn’t introduce any syntax errors by typing:

  1. sudo nginx -t

Next, restart Nginx:

  1. sudo systemctl restart nginx

Assuming that your Node.js application is running, and your application and Nginx configurations are correct, you should now be able to access your application via the Nginx reverse proxy. Try it out by accessing your server’s URL (its public IP address or domain name).

Conclusion

Congratulations! You now have your Node.js application running behind an Nginx reverse proxy on an Ubuntu 16.04 server. This reverse proxy setup is flexible enough to provide your users access to other applications or static web content that you want to share. Good luck with your Node.js development.

DigitalOcean provides multiple options for deploying Node.js applications, from our simple, affordable virtual machines to our fully-managed App Platform offering. Easily host your Node.js application on DigitalOcean in seconds.

Learn more here

About the author(s)

Brennen Bearnes
Brennen Bearnes
See author profile

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
60 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

pm2 startup systemd

should be change to

pm2 startup ubuntu

?

Brennen Bearnes
DigitalOcean Employee
DigitalOcean Employee badge
May 13, 2016

I actually didn’t have much luck with pm2 startup ubuntu, while pm2 startup systemd worked. I’m not sure whether PM2 has been updated for Ubuntu 16.04 at all yet, but it looks to still be aimed at Upstart rather than systemd. I’m guessing this will change eventually.

Thanks, for 14.04 it has to be the second one.

From what I’m reading elsewhere, PM2 has been made rather redundant due to the presence of systemd on these newer linux distros. See http://stackoverflow.com/questions/4018154/node-js-as-a-background-service

I’m hung up on running the Hello World app. I keep getting the error:

./hello.js: line 1: syntax error near unexpected token `('
./hello.js: line 1: `var http = require('http');'

I’ve tried inputting the code using nano and vi; and I’ve tried typing it and copy/pasting it, always deleting hello.js between attempts.

Any clues?

I figured it out. In this solution on Server Fault, I learned that the bash line needs to come first in the code. So lines one and two worked for me as:

#!/usr/bin/env nodejs
var http = require('http');
Brennen Bearnes
DigitalOcean Employee
DigitalOcean Employee badge
May 19, 2016

Good catch there - I managed to transpose those two lines when updating the tutorial. Fixed now.

it’s work for me. thanks jamethe500

This comment has been deleted

    I was on an nginx Odyssey that could have been avoided if the code snippet for /etc/nginx/sites-enabled/default under Configure Nginx for HTTPS showed it being wrapped in http { }. This was certainly a very rookie mistake, but that’s why I’m here in the first place. :) It’s all up and running now!

    For people searching, the error I was getting was nginx: [emerg] "server" directive is not allowed here in /etc/nginx/nginx.conf

    Brennen Bearnes
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 25, 2016

    The example here expects that /etc/nginx/nginx.conf contains a section like so:

    /etc/nginx/nginx.conf
    http {
            ...
            include /etc/nginx/conf.d/*.conf;
            include /etc/nginx/sites-enabled/*;
            ...
    }
    

    …it seems like this wasn’t the case on your system. Pre-existing configuration changes, possibly?

    using nvm + 16.04 + node 4.4.5 and running

    pm2 startup ubuntu
    

    and when i restart it it doesn’t load up the hello.js process…

    help!

    This is great. Do you have a tutorial on setting up passport to allow social logins. Most importantly, an explaination of how to ensure that site content isn’t accessible without logging in. I’ve tried this but seem to be missing the point of callback URIs. Also it seems that most tutorials out there don’t cover where to put your app on your server. I assume it doesn’t matter.

    For social logins, this should help:

    Passport.js Tutorial

    As pertaining to accessibility, I’m not sure if you’re referring to authentication or authorization. They differ in that one addresses route authorization for logged-in (authenticated) users and the other accessibility to hidden content. Content behind a password.

    I see that in this guide you put both the reverse proxy as well as the node server on one droplet. In the 14.04 guide, they used a separate droplet for the reverse proxy and a separate droplet for the node.js app.

    Could you explain the rationale a bit behind when and why it would be good to host these servers on separate droplets? For example, at what point would it start to make sense to look at using the nginx server as a load balancer and have multiple app droplets running in parallel?

    I’m trying to decide if we need multiple separate droplets for DB, app, nginx etc. or if we can get by with just one droplet for all three services at this stage.

    I’m also very interested on hearing about this, may someone please explain us about this? What’s better, to run everything on a single VPS or Dedicated Server? Or having different Dedicated Servers or VPS for each service? Also does anyone has an idea on what specs should I get to be able to run a Node.js website that has a Java service also and it is estimated to get around 500 to 1,000 visitors per month? So should I use VPS or Dedicated Servers for it? Also any guide on using Express.js to develop the Node.js app?

    Thanks!

    If you can afford it, it is best and more secure to separate your services. Your application and database servers should be running on a private network and should only be accessible via your reverse proxy.

    Why is the reverse proxy necessary or desirable? Can’t you just let node serve the app directly? Does using a proxy interfere with socket.io communication between server/client?

    You typically don’t want to expose your application server to direct traffic on port 80. If you want to scale your application, you will have multiple application servers running, and the reverse proxy can act as a load balancer and spread the requests out among the application servers: http://imgur.com/a/rKcy7

    The application servers should also be running on a VPN or private network. This prevents outside communication and ensures only the reverse proxy is talking to it. This also allows for SSL termination

    Hey, just found an error:

    The “server_name” line needs to appear in the HTTP block, not the HTTPS block.

    Placing it in the first block produces perfect results.

    Phenomenal walk through, Digital Ocean puts it down.

    I’m getting this error when I try to retrieve the initial certificate:

    run this:

    $ ./letsencrypt-auto certonly --standalone
    

    and get this:

    Failed authorization procedure. fooproject.com (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Failed to connect to 000.000.000.000:443 for TLS-SNI-01 challenge,
    

    not my actual domain name or ip address pasted above

    Shouldn’t let’s encrypt be trying to connect to port 80?

    Looks like you haven’t pointed your domain to the server / vps / droplet where you are trying to install the Let’s Encrypt certificate.

    This comment has been deleted

      In what folder should I start developing my Node.js Application? I plan on creating a MEAN (MongoDB, Express.js, Angular.js, Node.js) Application but I don’t know if I should place it on a folder like /var/www/{my_project_name} or should it be on /home/{my_username}/{my_project_name} or on /home/{dedicated_username_for_the_project}/{my_project_name} ?

      this.

      For those, who using CloudFlare and getting error after Let’s Encrypt attempt, read this

      TL;DR:

      1. You don’t need to stop nginx
      2. Instead of using
      $ ./letsencrypt-auto certonly --standalone
      

      use:

      $ ./letsencrypt-auto certonly --webroot --webroot-path /var/www/YOUR_WWW_PATH/ --renew-by-default --email YOURMAIL@example.com --text --agree-tos -d YOURDOMAIN.com -d www.YOURDOMAIN.com
      

      Also I had error after ./letsencrypt-auto certonly --standalone

      Creating virtual environment...
      Traceback (most recent call last):
        File "/usr/lib/python3/dist-packages/virtualenv.py", line 2363, in <module>
          main()
        File "/usr/lib/python3/dist-packages/virtualenv.py", line 719, in main
          symlink=options.symlink)
        File "/usr/lib/python3/dist-packages/virtualenv.py", line 988, in create_environment
          download=download,
        File "/usr/lib/python3/dist-packages/virtualenv.py", line 918, in install_wheel
          call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT)
        File "/usr/lib/python3/dist-packages/virtualenv.py", line 812, in call_subprocess
          % (cmd_desc, proc.returncode))
      OSError: Command /.local/s...ncrypt/bin/python2.7 - setuptools pkg_resources pip wheel failed with error code 1
      

      In my case, before running letsencrypt-auto:

      $ export LC_ALL="C"
      

      did the trick.

      This tutorial worked before. But since I stop nginx, when I try to start it again. It dose not listen on 8080 any more. When I run

      lsof -i :8080
      

      it returns nothing now.

      When I open my website, it shows:

      502 Bad Gateway

      What may cause this? Thanks

      Oh, it is because pm2 is building my app. After it finish building the app, it works again.

      Just add another comment, if you need http2, it is quite simple, just change

      listen 443;
      

      to

      listen 443 http2;
      

      if you have this error: npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.0.14: wanted {“os”:“darwin”,“arch”:“any”} (current: {“os”:“linux”,“arch”:“x64”}) ubuntu

      *you can use this line ** : * sudo npm install -g npm@3.8.9

      Hey guys! I’ve written a script that does all of this with just one line of code pasted into the terminal!

      https://github.com/marcotriglia/ubuntu_16.04_nodejs_server_setup

      Give it a star if you like it, it would mean a lot!

      Thank you for this, it seems to work fine. I was having trouble setting it up on my own.

      The guide says you should be doing this with “a non-root user with sudo privileges”, but it seems like everything is done with the root profile. Are there any repercussions to doing it this way? Should I still create another user?

      Hi skeddtemp,

      We should always follow something called ‘Principle of Least Privilege’ ( https://en.wikipedia.org/wiki/Principle_of_least_privilege ): a user should only have those privileges essential to their work. This makes it so that we don’t accidentally run some actions that could damage the system or that if someone gains access to our account s/he doesn’t have all privileges on the computer.

      By running commands with sudo (superuser do - pronounced ‘sue doo’), you’re telling the computer that you want them to be executed as if you were on the root profile (you can try this yourself by going into terminal and typing sudo whoami from a non-root user - it will ask for a password). This allows us to be root only when we need something to have superuser access, but remain a regular user at all other times.

      Hope that cleared things up!

      Marco

       proxy_ssl_session_reuse off;
      

      for what reason? There is no any ssl connection to the upstream:proxy_pass http://...

      -systemd- Using the command: su sammy -c “pm2 dump && pm2 kill” && su root -c “systemctl daemon-reload && systemctl enable pm2 && systemctl start pm2” Command failed: /bin/sh -c su sammy -c “pm2 dump && pm2 kill” && su root -c “systemctl daemon-reload && systemctl enable pm2 && systemctl start pm2” bash: systemctl: command not found

      I did change sammy to my user account.

      I have an NGINX PHP (WordPress) site in the root and I want to have a Node.js app (Meteor, Angular2, MongoDB) at https://mydomain.com/nodeapp

      How shall the NGINX /etc/nginx/sites-enabled/digitalocean file look like? (I installed using the DigitalOcean UBUNTU 16.04 LEMP image, that’s why the config file is called digitalocean…)

      I’m getting a…

      The mydomain.com page isn’t working. mydomain.com redirected you too many times.

      ERR_TOO_MANY_REDIRECTS

      Could anyone think of a reason why this would be happening? I followed the tutorial very closely. The only thing that I could think that may be causing an error are my subdomains. I can give more information.

      I followed the guide but some how response from nginx proxy reverse is wrapped in <pre> tags. But when i access the droplet ip with the port to node app is working fine.

      I followed this tutorial to setup node react app, but it take 20 sec to load a page which should be very less, What configuration need to change in order to load page normally?

      How would you setup a ssl certificate both for www.mydomain.com and mydomain.com using SAN?

      While setting up the reverse proxy using localhost:

      proxy_pass http://localhost:8080;
      

      It sometimes spits out a 502 error. This may happen due an infinite loop of domain forwarding. To avoid this, use ip address instead of localhost or 127.0.0.1 like as follows.

      proxy_pass http://255.255.255.255:8080;
      

      replace 255.255.255.255 by your external ip address

      Also, if you need to point this to a subdomain instead of main domain or any directory path:

      server {
          		listen 80;
      		server_name SUBDOMAIN.DOMAIN.com;
      		location / {
              proxy_pass http://IP_ADDRESS:8080; //ip address or localhost or domain name. Make sure it doesn’t fall in an infinite loop of redirects. IP address is safest option but it’s a situational thing
              		        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;
          		}
      }
      
      

      How can I expose another Express app on another port publicly? (i.e. one express app running on port 8080 is served publicly on port 80, while a second express app running on port 8081 is served publicly on port 8008)

      In my /etc/nginx/sites-available/default file I added the following server block directly after the 443 ssl server.

      server {
        listen 8008 ssl;
        server_name example.com www.example.com;
      
        include snippets/ssl-example.com.conf;
        include snippets/ssl-params.conf;
      
        # pass requests to port 8081 where our other node server is running
        location / {
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-NginX-Proxy true;
          proxy_pass http://localhost:8081/;
          proxy_ssl_session_reuse off;
          proxy_set_header Host $http_host;
          proxy_cache_bypass $http_upgrade;
          proxy_redirect off;
        }
      }
      

      Currently, all public traffic (http or https) to port 8008 results in a timeout. Hitting the app locally over https (i.e. https://example.com:8008) results in a success response, while hitting the app locally over http (i.e. http://example.com:8008) results in 400 The plain HTTP request was sent to HTTPS port.

      The desired behavior is that all public http traffic continues to be redirected to https, and the second express app is available publicly at https://example.com:8008.

      I’ve been wrestling with this for over a day now. Any help or guidance would be much appreciated! :)

      I am getting https : Secure on the URL bar, but the website is not loaded. I am getting this error:

      ** 502 Bad Gateway

      nginx/1.10.0 (Ubuntu)**

      Any suggestions on this one ?

      In the SSL configuration with LetsEncrypt, the following line needs to be changed from;

      listen 443;
      

      to

      listen 443 ssl;
      

      This is as per instructions from Nginx http://nginx.org/en/docs/http/configuring_https_servers.html

      -systemd- Using the command: su sammy -c “pm2 dump && pm2 kill” && su root -c “systemctl daemon-reload && systemctl enable pm2 && systemctl start pm2” Command failed: /bin/sh -c su sammy -c “pm2 dump && pm2 kill” && su root -c “systemctl daemon-reload && systemctl enable pm2 && systemctl start pm2” bash: systemctl: command not found

      I did change sammy to my user account.

      I have an NGINX PHP (WordPress) site in the root and I want to have a Node.js app (Meteor, Angular2, MongoDB) at https://mydomain.com/nodeapp

      How shall the NGINX /etc/nginx/sites-enabled/digitalocean file look like? (I installed using the DigitalOcean UBUNTU 16.04 LEMP image, that’s why the config file is called digitalocean…)

      I’m getting a…

      The mydomain.com page isn’t working. mydomain.com redirected you too many times.

      ERR_TOO_MANY_REDIRECTS

      Could anyone think of a reason why this would be happening? I followed the tutorial very closely. The only thing that I could think that may be causing an error are my subdomains. I can give more information.

      I followed the guide but some how response from nginx proxy reverse is wrapped in <pre> tags. But when i access the droplet ip with the port to node app is working fine.

      I followed this tutorial to setup node react app, but it take 20 sec to load a page which should be very less, What configuration need to change in order to load page normally?

      How would you setup a ssl certificate both for www.mydomain.com and mydomain.com using SAN?

      While setting up the reverse proxy using localhost:

      proxy_pass http://localhost:8080;
      

      It sometimes spits out a 502 error. This may happen due an infinite loop of domain forwarding. To avoid this, use ip address instead of localhost or 127.0.0.1 like as follows.

      proxy_pass http://255.255.255.255:8080;
      

      replace 255.255.255.255 by your external ip address

      Also, if you need to point this to a subdomain instead of main domain or any directory path:

      server {
          		listen 80;
      		server_name SUBDOMAIN.DOMAIN.com;
      		location / {
              proxy_pass http://IP_ADDRESS:8080; //ip address or localhost or domain name. Make sure it doesn’t fall in an infinite loop of redirects. IP address is safest option but it’s a situational thing
              		        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;
          		}
      }
      
      

      How can I expose another Express app on another port publicly? (i.e. one express app running on port 8080 is served publicly on port 80, while a second express app running on port 8081 is served publicly on port 8008)

      In my /etc/nginx/sites-available/default file I added the following server block directly after the 443 ssl server.

      server {
        listen 8008 ssl;
        server_name example.com www.example.com;
      
        include snippets/ssl-example.com.conf;
        include snippets/ssl-params.conf;
      
        # pass requests to port 8081 where our other node server is running
        location / {
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-NginX-Proxy true;
          proxy_pass http://localhost:8081/;
          proxy_ssl_session_reuse off;
          proxy_set_header Host $http_host;
          proxy_cache_bypass $http_upgrade;
          proxy_redirect off;
        }
      }
      

      Currently, all public traffic (http or https) to port 8008 results in a timeout. Hitting the app locally over https (i.e. https://example.com:8008) results in a success response, while hitting the app locally over http (i.e. http://example.com:8008) results in 400 The plain HTTP request was sent to HTTPS port.

      The desired behavior is that all public http traffic continues to be redirected to https, and the second express app is available publicly at https://example.com:8008.

      I’ve been wrestling with this for over a day now. Any help or guidance would be much appreciated! :)

      I am getting https : Secure on the URL bar, but the website is not loaded. I am getting this error:

      ** 502 Bad Gateway

      nginx/1.10.0 (Ubuntu)**

      Any suggestions on this one ?

      In the SSL configuration with LetsEncrypt, the following line needs to be changed from;

      listen 443;
      

      to

      listen 443 ssl;
      

      This is as per instructions from Nginx http://nginx.org/en/docs/http/configuring_https_servers.html

      After replacing the contents of the default file with the code provided in the Configure Nginx for HTTPS section, I’m getting the following error.

      nginx: [emerg] duplicate listen options for [::]:80 in /etc/nginx/sites-enabled/default~:4
      nginx: configuration file /etc/nginx/nginx.conf test failed
      

      I’m not sure why line 4 would be having a problem since that part stays the same after copying the text. Does anyone know what could be causing this problem?

      Awesome tutorial!! Thanks!!!

      Hello,

      I found this tutorial very helpful, I got my site up and running with https and I’m receiving ‘hello world’ in the browser. However, I’d like to add a sub-domain which is going to be running on the same droplet (my root is blakehschwartz.com and I’d like to add portfolio.blakehschwartz.com.) I’ve looked at a couple of other tutorials as well, and can’t figure out if I can just add to my existing server block or if I need to add a separate one (this one mentions using separate server blocks, but the config also looks a lot more manual/hard-coded). I’m also unsure if I can piggy back off my existing root domain ports or if I need to assign new ones (seems like I should be able to use 80 and 443 for the public part and maybe use localhost:8081 for the proxy part.

      Also, like another asked a while back - where do I place my web files for the root and subdomains? In the past I’ve used shared hosting where each one had it’s own ftp directory, and I just put everything in /var/www/html respectively. It looks like nginx is using location / to reference /var/www/html since that’s where my helloworld.js file is, but how would that work with a subdomain?

      Here’s my current server block for reference:

      # HTTP - redirect all requests to HTTPS:
      server {
              listen 80;
              listen [::]:80 default_server ipv6only=on;
              return 301 https://$host$request_uri;
      }
      
      # HTTPS - proxy requests on to local Node.js app:
      server {
              listen 443;
              server_name blakehschwartz.com;
      
              ssl on;
              # Use certificate and key provided by Let's Encrypt:
                      <ssl stuff>
      
              # Pass requests for / to localhost:8080:
              location / {
                      <proxy stuff>
              }
      }
      
      

      Any help would be great, thanks!

      thanks for this guide! super helpful and explains all the right things. i’ve used it to set up a few servers already.

      hi I can’t get my helloworld app working — when I curl http://localhost:8080 I’m getting there error:

      curl: (7) Failed to connect to localhost port 8080: Connection refused

      I’ve tried destroying and rebuilding the droplet to make sure everything is installed properly but got same error. Any suggestions?

      This is a great article, as all of these tutorials are. I do want to suggest an addendum, though.

      I started up an Express app using the express-session module (connected to Redis) to manage user sessions, and I had a heck of a time figuring out why secure cookies weren’t working. The main key seems to have been that I needed to set this in the sites-available file for the reverse proxy configuration block:

      proxy_set_header X-Forwarded-Proto $scheme
      

      It’s talked about in this article a bit, though not in the context of Node. https://www.digitalocean.com/community/tutorials/understanding-nginx-http-proxying-load-balancing-buffering-and-caching

      I also set the trust proxy in the Express app and specifically set the proxy setting to true in my session config. But the main thing was just to convey secure connection info from Nginx to Node.

      This worked to get pm2, itself, to run after restarting Linux, but it wasn’t actually restarting any of the Node processes. For that, I needed to do:

      pm2 save
      

      As mentioned on the pm2 Startup usage page. After that, pm2 would start my Node app after a Linux reboot.

      In case anyone is having problems with websockets throwing errors when trying to set up HTTPS:

      WebSocket connection to 'ws://.../socket.io/?EIO=2&transport=websocket&sid=p3af7ZNfvogtq6tAAAG0' failed: Error during WebSocket handshake: Unexpected response code: 400.
      

      Add the following to your configuration:

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

      The solution was found on an issue opened on the socket-io repo: Error during WebSocket handshake: Unexpected response code: 400

      I have a question, I made all the process for a Front End app and I got the https to work on a domain, now I trying to implement https in the API works with the Front-End in the same server but of course in a different port. No matters what I do I keep getting this error 400 The plain HTTP request was sent to HTTPS port Can anybody help me?

      Hello everyone, My name is Q, I’m now a developer for my site. I use 1 droplet 5$ for MongoDB and 1 for Nodejs(API service)

      The issue here is when i deploy my Node app( all the steps before deploying are done with no errors) using PM2( the PM2 listed app as online and command curl to the ip:port of app works just fine) the app cant be reached by browser

      Link: 128.199.177.41:3001/apis/…( run at port 3001, … could be /accounts/verify which get a JSON msg)

      Please help me! Thank you in advance!

      P/s: Previously, I have my old server(also 5$ droplet on Digital Ocean) running just fine

      Turns out when installing and configuring pm2 IT IS ABSOLUTELY IMPERATIVE that to execute none of those commands as root AND that you do NOT use sudo in any of the commands where sudo is not shown in the article. D.O support might advise you otherwise. But take my word for it. To not most likely will drive you mad.

      When using nginx as a reverse proxy with http2, is it advisable to use spdy npm on the node/express end as well? Or is it better to leave that on http behind the scenes?

      what if there is Apache server already installed ? can both install (Apache and NginX) at one server providing two applications such as Apache for HTML/PHP based application and nGinx for Node JS application ?

      Thanks

      Thanks for the tutorial - i was able to set it up as described but am facing an issue with renewing my letsencrypt certificate now - when I run the cron process to renew the certificate, it gives an error saying the renewal failed.

      Could this be due to nginx acting as a reverse proxy?

      I have set up the reverse proxy exactly as described here and am calling my node app which listens to a localhost port as shown in this tutorial.

      This is the error I am getting: produced an unexpected error: Problem binding to port 443: Could not bind to IPv4 or IPv6… Skipping.

      Output [PM2] Init System found: systemd [PM2] You have to run this command as root. Execute the following command: sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u sammy --hp /home/sammy

      I don’t see any of this? Why?

      Great article! Never thought it’s that easy to host multiple node apps on one droplet.

      Just one nitpick, there should be a trailing / for the line in /etc/nginx/sites-available/default file. Without it, I was getting 404’s from my apps.

      proxy_pass http://localhost:8081/;
      

      Great tutorial!

      I want to try out the nginx function, config my location block to location /app2 { ... }, then browse my website by domain.com/app2. Turns out nodejs return “Cannot GET /app2”.

      It works if just location / { ... }.

      I am new to nodejs & nginx, can anyone tell me what is happening?

      Thanks for this excellent article

      Starting processes that receive command line argument, e.g.

      pm2 start server.js --name MyServer -- -h localhost -p 8080
      

      requires a dump of the running process list to be saved using

      pm2 save
      

      in order for the processes to start again after reboot using systemd. I don’t know if this is also true for processes that don’t need arguments, but this is at least the case for me.

      So I think this guide should contain something about pm2 save

      Hi, thanks for great tutorial!

      Is it possible to run separate node apps on different routes, using SSL?

      If no can you guys tell me, how can i disable non https redirect to https? thanks!

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Become a contributor for community

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      DigitalOcean Documentation

      Full documentation for every DigitalOcean product.

      Resources for startups and SMBs

      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

      Get our newsletter

      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

      New accounts only. By submitting your email you agree to our Privacy Policy

      The developer cloud

      Scale up as you grow — whether you're running one virtual machine or ten thousand.

      Get started for free

      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

      *This promotional offer applies to new accounts only.