Node.js is an open source Javascript runtime environment for easily building server-side and networking applications. The platform runs on Linux, OS X, FreeBSD, and Windows, and its applications are written in JavaScript. Node.js applications can be run at the command line but we will teach you how to run them as a service, so they will automatically restart on reboot or failure, so you can use them in a production environment.
In this tutorial, we will cover setting up a production-ready Node.js environment that is composed of two Ubuntu 14.04 servers; one server will run Node.js applications managed by PM2, while the other will provide users with access to the application through an Nginx reverse proxy to the application server.
The CentOS version of this tutorial can be found here.
This guide uses two Ubuntu 14.04 servers with private networking (in the same datacenter). We will refer to them by the following names:
It is possible to use a single server for this tutorial, but you will have to make a few changes along the way. Simply use the localhost IP address, i.e. 127.0.0.1
, wherever the app server’s private IP address is used.
Here is a diagram of what your setup will be after following this tutorial:
Before you begin this guide, you should have a regular, non-root user with sudo
privileges configured on both of your servers–this is the user that you should log in to your servers as. You can learn how to configure a regular user account by following steps 1-4 in our initial server setup guide for Ubuntu 14.04.
If you want to be able to access your web server via a domain name, instead of its public IP address, purchase a domain name then follow these tutorials:
Let’s get started by installing the Node.js runtime on the app server.
We will install the latest LTS release of Node.js, on the app server.
On the app server, let’s update the apt-get package lists with this command:
Then use apt-get
to install the git
package, which npm
depends on:
Go to the Node.js Downloads page and find the Linux Binaries (.tar.xz) download link. Right-click it, and copy its link address to your clipboard. At the time of this writing, the latest LTS release is 4.2.3. If you prefer to install the latest stable release of Node.js, go to the appropriate page and copy that link.
Change to your home directory and download the Node.js source with wget
. Paste the download link in place of the highlighted part:
Now extract the tar archive you just downloaded into the node
directory with these commands:
If you want to delete the Node.js archive that you downloaded, since we no longer need it, change to your home directory and use this rm
command:
Next, we’ll configure the global prefix
of npm
, where npm
will create symbolic links to installed Node packages, to somewhere that it’s in your default path. We’ll set it to /usr/local
with this command:
Now we’re ready to move the node
and npm
binaries to our installation location. We’ll move it into /opt/node
with this command:
At this point, you may want to make root
the owner of the files:
Lastly, let’s create symbolic links of the node
and npm
binaries in your default path. We’ll put the links in /usr/local/bin
with these commands:
Verify that Node is installed by checking its version with this command:
The Node.js runtime is now installed, and ready to run an application! Let’s write a Node.js application.
Now we will create a Hello World application that simply 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 it with your own application–just make sure that you modify your application to listen on the appropriate IP addresses and ports.
Because we want our Node.js application to serve requests that come from our reverse proxy server, web, we will utilize our app server’s private network interface for inter-server communication. Look up your app server’s private network address.
If you are using a DigitalOcean droplet as your server, you may look up the server’s private IP address through the Metadata service. On the app server, use the curl
command to retrieve the IP address now:
You will want to copy the output (the private IP address), as it will be used to configure our Node.js application.
Next, create and open your Node.js application for editing. For this tutorial, we will use vi
to edit a sample application called hello.js
:
Insert the following code into the file, and be sure to substitute the app server’s private IP address for both of highlighted APP_PRIVATE_IP_ADDRESS
items. If you want to, you may also replace the highlighted port, 8080
, in both locations (be sure to use a non-admin port, i.e. 1024 or greater):
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8080, 'APP_PRIVATE_IP_ADDRESS');
console.log('Server running at http://APP_PRIVATE_IP_ADDRESS:8080/');
Now save and exit.
This Node.js application simply listens on the specified IP address and port, and returns “Hello World” with a 200
HTTP success code. This means that the application is only reachable from servers on the same private network, such as our web server.
If you want to test if your application works, run this node
command on the app server:
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 and connect to your web server. Because the web server is on the same private network, it should be able to reach the private IP address of the app server using curl
. Be sure to substitute in the app server’s private IP address for APP_PRIVATE_IP_ADDRESS
, and the port if you changed it:
If you see the following output, the application is working properly and listening on the proper IP 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 IP address and port.
On the app server, be sure to kill the application (if you haven’t already) by pressing CTRL+C
.
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 as a service).
We will use Node Packaged Modules (NPM), which is basically a package manager for Node modules that installs with Node.js, to install PM2 on our app server. Use this command to install PM2:
PM2 is simple and easy to use. We will cover a few basic uses of PM2.
The first thing you will want to do is use the pm2 start
command to run your application, hello.js
, in the background:
This also adds your application to PM2’s process list, which is outputted every time you start an application:
Output:┌──────────┬────┬──────┬──────┬────────┬───────────┬────────┬────────────┬──────────┐
│ App name │ id │ mode │ PID │ status │ restarted │ uptime │ memory │ watching │
├──────────┼────┼──────┼──────┼────────┼───────────┼────────┼────────────┼──────────┤
│ hello │ 0 │ fork │ 5871 │ online │ 0 │ 0s │ 9.012 MB │ disabled │
└──────────┴────┴──────┴──────┴────────┴───────────┴────────┴────────────┴──────────┘
As you can see, PM2 automatically assigns an App 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. You must also specify the platform you are running on, which is ubuntu
, in our case:
The last line of the resulting output will include a command (that must be run with superuser privileges) that you must run:
Output:[PM2] You have to run this command as root
[PM2] Execute the following command :
[PM2] sudo su -c "env PATH=$PATH:/opt/node/bin pm2 startup ubuntu -u sammy --hp /home/sammy"
Run the command that was generated (similar to the highlighted output above) to set PM2 up to start on boot (use the command from your own output):
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
):
Restart an application with this command (specify the PM2 App name
or id
):
The list of applications currently managed by PM2 can also be looked up with the list
subcommand:
More information about a specific application can be found by using the info
subcommand (specify the PM2 App name or id)::
The PM2 process monitor can be pulled up with the monit
subcommand. This displays the application status, CPU, and memory usage:
Now that your Node.js application is running, and managed by PM2, let’s set up the reverse proxy.
Now that your application is running, and listening on a private IP address, you need to set up a way for your users to access it. We will set up an Nginx web server as a reverse proxy for this purpose. This tutorial will set up an Nginx server from scratch. If you already have an Nginx server setup, you can just copy the location
block into the server block of your choice (make sure the location does not conflict with any of your web server’s existing content).
On the web server, let’s update the apt-get package lists with this command:
Then install Nginx using apt-get:
Now open the default server block configuration file for editing:
Delete everything in the file and insert the following configuration. Be sure to substitute your own domain name for the server_name
directive (or IP address if you don’t have a domain set up), and the app server private IP address for the APP_PRIVATE_IP_ADDRESS
. Additionally, change the port (8080
) if your application is set to listen on a different port:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://APP_PRIVATE_IP_ADDRESS: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 web server to respond to requests at its root. Assuming our server is available at example.com
, accessing http://example.com/
via a web browser would send the request to the application server’s private IP address on port 8080
, which would be received and replied to by the Node.js application.
You can add additional location
blocks to the same server block to provide access to other applications on the same web server. For example, if you were also running another Node.js application on the app server on port 8081
, you could add this location block to allow access to it via http://example.com/app2
:
location /app2 {
proxy_pass http://APP_PRIVATE_IP_ADDRESS: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.
On the web server, restart Nginx:
Assuming that your Node.js application is running, and your application and Nginx configurations are correct, you should be able to access your application via the reverse proxy of the web server. Try it out by accessing your web server’s URL (its public IP address or domain name).
Congratulations! You now have your Node.js application running behind an Nginx reverse proxy on Ubuntu 14.04 servers. 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!
Also, if you are looking to encrypt transmissions between your web server and your users, here is a tutorial that will help you get HTTPS (TLS/SSL) support set up.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
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!
Why use a proxy?
It’s insecure to run any node app at 80 port (because only root have access to ports 0-1024, and in this case nodejs must run with root privileges). See https://groups.google.com/forum/?fromgroups=#!topic/nodejs/gB8veFbcX5g
What’s the reason that the nginx server is run on a separate droplet? Is it also security-related?
Security - If you proxy server gets compromised, your app server might still be fine. Scalability&Flexibility - It’s really easy to switch the app server. It’s also easier to scale the proxy&app servers horizontally and vertically with this setup.
Is it insecure even with setcap to run on port 80?
+1 for it being insecure. But if a process can be hijacked thru http putting nginx in front of it won’t help, except the attacker won’t have root access, but if it has vulnerabilities exposed over tcp or other underlying protocol, nginx can save you.
Better question: Why run the nginx server on a separate droplet?
What could be the reason I’m getting the error EADDRNOTAVAIL when executing
node hello.js
?I’m having the same problem. It seem to work when I switch it to my public ip… Did you ever figure out how to fix it?
Are both of your servers in the same data center with private networking?
Same problem for me, On the initial droplet setup I forgot to set private networking, so I stopped the droplet turned private networking on and restarted, but still get the same issue, any ideas. This is before any interaction with the web server, so can only assume the app server is at fault somewhere.
Creating from scratch with private networking turned on, fixes the issue.
If you create a droplet without private networking then enable private networking later, you must set up the new network interface on your system: How To Enable DigitalOcean Private Networking on Existing Droplets.
god, can they just say something on the private network page, point to this article as manicas pointed out, took me forever to find out.
I had a similar issue. For me, it was because a prerequisite tutorial had disallowed port 3000. If you followed a previous tutorial, try
sudo ufw allow 3000/tcp
run
pm2 stop hello.js
If we are using nginx here, maybe we can use some additional cache settings? So nginx can serve all static files, and node will wake up only for executing some logic.
Definetly. This is just an example of how to set up the basic infrastructure. For a deeper dive into what you can do with Nginx, check out:
If I want to run my node.js app across 3 nodes with multi-core processors, PM2 can help me achieve that? I know PM2 helps me run my app across a single server with multi-core support, but if I have more nodes, Can I use PM2 or need a load-balancer like Haproxy or Nginx Proxy?
Digital Oceans always on top of their game. I have been using Monit and Upstart directly, but this seems like a quicker alternative. Thanks.
What are the advantages of suing PM2 vs using something like nodejs forever + nohup?
Basically, PM2 has more features. Both can be used to keep an application running.
Great tutorial, but why you are not using NPM to install node instead? @manicas Secondly, if we are using only a single server to be APP and WEB, what would it affect?
You can use a single server to run both components (I think it’s mentioned in the tutorial somewhere). Separating them makes scaling easier, and isolates the web tier from the applications.
Thanks @manicas I found out that using node v0.12 requires twice of this steps to complete installation of node:
*Configure and build Node.js with the following commands: ./configure make
Now, to install Node.js, run this command sudo make install*
I hope it helps for the future install.
Cheers
npm is part of node… so is it even possible to use it to install node?
hi Please could you tell me … Is it Ok (good ?) to use for creating the app server the image “Node -v 0.12 on 14.04” provided under the *“Create Droplet -Application” * menu ?
That’s what I’m doing an it’s working fine. As far as I’m aware it just means you get to skip the installing node bit.
Does it also work with node+socket.io (two way communication)?
Hi! i have this:
g++: internal compiler error: Killed (program cc1plus) Please submit a full bug report, with preprocessed source if appropriate. See <file:///usr/share/doc/gcc-4.8/README.Bugs> for instructions. make[1]: *** [/root/node-v0.12.0/out/Release/obj.target/v8_base/deps/v8/src/api.o] Error 4 make[1]: Leaving directory `/root/node-v0.12.0/out’ make: *** [node] Error 2
What happened?
Wonderful stuff! Question is how can I prevent directory browsing of my root folder when running my app in Ubuntu? Can nginx help me save my world in this case? if I run my web server on port 8000 and my rest api on 8001 how can nginx help me start both in one command :(
Just create a separate server block for each app (listening port). Check out this tutorial: How To Set Up Nginx Server Blocks
@manicas I’m kind of confused on what the following do to the HTTP headers:
What is HTTP Upgrade? How does that have to do with reverse proxy?
Those headers are necessary when proxying a WebSocket.
Also how does the nginx built-in load balancer compare to pm2’s?
I haven’t used it, but I believe the PM2 load balancer performs load balancing at the Node process level, where Nginx is used for network load balancing.
This was a really excellent guide, just the info I needed to get started, thanks!
Thanks for the guide. I assuming that if I configure nginx accordingly I can use this set up for a) multiple domains, and b) multiple app servers. Am I correct in that assumption?
Yes, that is correct.
@manicas, great tutorial.
My connection was hanging until I commented out the following line,
Do you have any idea why this would happen?
Thank you for this. I was stuck on a 502 Bad Gateway error for awhile until I scrolled deep into the comments and found this. Removed the line and poof it works. Thanks. Wish I knew why that fixed everything but for now I’ll take the win.
When using nginx I am able to access my nodejs app at the URL myapp.com/home, but if I navigate to myapp.com I still get the nginx welcome page. Is there a fix for this?
Did you set your
location
directive to “/home” ? It should look like this:Thanks Mitchell. Wonderful post and has helped us setting our Nodejs production environment. We are facing issue where Nginx is not severing updated HTML files which is part of one nodejs application.
Do Ngnix cache all static contents by default? If yes, then what is the location of caching in Ubantu? Or it doesnt cache, can you pls help with providing required conf setting for this. Googled alot but not able to find the solution.
By default, nginx does not cache any files. You can configure nginx so serve static files and pass everything else to Node.js like this:
Great post! Now I’m truly ready for production. Digital Ocean you are really good!
Stupid question, but which droplet should the actual domain name (e.g. example.com) be registered to: the WEB droplet or the APP droplet?
The WEB droplet (the reverse proxy web server) is the server that users will access, so your domain name should point there.
If your domain is using the DigitalOcean DNS, you can follow this tutorial for help on setting that up: How To Set Up a Host Name with DigitalOcean.
I get this, whats missing or wrong ?
pm2 hello.js [PM2] Spawning PM2 daemon Error: spawn ENOENT at errnoException (child_process.js:988:11) at Process.ChildProcess._handle.onexit (child_process.js:779:34) Error: spawn ENOENT at errnoException (child_process.js:988:11) at Process.ChildProcess._handle.onexit (child_process.js:779:34) Did you forgot to call pm2.connect(function() { }) before interacting with PM2 ?
the part about PM2 will save my life some day…
I have read dozens of other ways to restart an app after reboot but NONE worked. Maybe because my app runs in /home/myUser and this is not yet ready when the server boots and the configured files are started?
Well, PM2 works well.
Actually: today a digital ocean server went down momentarily (first time in two years and about 6 apps) and my application didn’t restart after reboot - that’s why I finally found this article. It won’t happen again!
thanks!
Thank you! This was really informative and well explained! I only had one problem, but the problem did not stop me from setting everything up. Running sudo npm install pm2 -g gave me errors regarding git. I realized I did not have git installed. But even after installation of git I got a new error: “npm WARN optional dep failed, continuing fsevents@0.3.6”
Well, Its working atleast! I am also just using one server.
I couldn’t get my private ip address, what should i input to my command prompt exactly?
Try
ip addr
orifconfig
Extremely easy to follow and just what I needed to deploy! Thanks!
Very nice tutorial, nginx is returning a 404, after a redirect from my node app to a static login page (the login page didn’t load. should i have another configuration if node is using ui-route? or does it have a conflict with static content being serve by node?
I’m not sure what your app or configuration looks like, but you may have to configure nginx URL rewrites.
In my application with nodejs + redis + rails, can i use this configuration for node and use this (https://www.digitalocean.com/community/tutorials/how-to-deploy-a-rails-app-with-passenger-and-nginx-on-ubuntu-14-04) for my rails app? With some changes, off course.
Could you describe your setup?
Great tutorial! Works perfectly for me.
You can start a droplet with nodejs already installed, is it safe to skip your install step? or is there something different compared to yours.
Yes, the one-click lets you skip the Install Node.js section.
Adding additional locations other than a root ‘/’ domain it not working for me. The additional locations just redirects to the default nginx page or to the app deployed to / (if any)
In the example below /uds will redirect to the default nginx page if I replace the /uds with / - it’s getting to my node app.
Hi I followed this blog. I am using one Digital Ocean droplet to set up. I end up with a error of 502 Bad Gateway.
Do you know what I can do to fix this?
Double check which port and IP address your Node app is listening on (
}).listen(8080, '10.10.10.10'); , and make sure your Nginx configuration matches that (
proxy_pass http://10.10.10.10:8080;`). Then restart your app and Nginx. If your app is on the same server as Nginx, you can use localhost instead of the private IP address.Thanks for the amazing tutorial! Really helped! One problem: when I access my app by it’s domain+port like http://www.site.com:8000 it works fine, I can see all data and all. But when I access without the port, it doesn’t show any of the data. Weird part: when I add data from the address WITHOUT the port, it adds normally, but shows only on the app WITH the 8000 port, and not on the one without port. What should I do?
Hi everybody, I do not understand why sometines you do use sudo and sometines you don’t.
Hi. As a user, you usually have write access to your home directory only (and some other directories that are usually writeable by everyone, such as
/tmp
). In order to use commands that need write access to system files likeapt-get
that installs programs globally outside of your home directory, you need to escalate toroot
which has access to everything on the server.sudo
is a command that it used to run commands and programs as a different user, which isroot
by default.I always read on the web that node.js web applications should work under non root user like user1 for the example. But if we use sudo too under user1, files and directories for the application belong to user1 but belong to root group. So, is it a security problem to do that way or not ? That is the question…
Hello, I have a problem, with this settings nginx doesnt load the website when accessed with “www.” because it’s a subdomain, how can I do this? I have tried this in nginx config default ( /etc/nginx/sites-available/default ) : server { listen 80; server_name www.domain.com; return 301 $scheme://domain.com$request_uri; }
server { listen 80;
}
I found this in stackoverflow but it doesnt work, how can i make www. to redirect to non-www or at least be able to see the website also with www?
Thank you for your help!
Did you add the necessary DNS records? Check out this tutorial: How To Redirect www to Non-www with Nginx on Ubuntu 14.04
Thank you manicas, I’ve found the info some minutes after posting my comment.
Thanks, interesting and informative read!
Hello,
I am newbie in administration of server. Should I use two droplets with ubuntu for this example? Did I understand it right?
Hi. Yes, the tutorial is for two Droplets. However, you can set it up on a single Droplet as well.
Node source mentioned is very old. Current Node version 5.0.0
Would be nice to see the article being updated once in a while…
Current Node is newer, but it’s likely that many people running Node in production are using the 4.x because it’s LTS.
is it possible to setup 2 reverse proxy to point to Node.js application server ?
Yes, you can point two reverse proxies to the same application server.
Awesome tutorial! Been using this on my droplet for a while and it all worked well. But now when I’m updated my source code and done ubuntu updates, nginx/pm2 crashed and I dont have any idea why really. For starter I had a problem running pm2 without “sudo” but I think I figured that out, and now to the remaining problem: When visiting the site in the browser I get 502 Bad gateway, and when looking at the log I get this:
and I dont get any errors when running nginx -t. So a little out of my knowledge right now.
Have been looking around in the nginx files and /etc/nginx/sites-available/default and /etc/nginx/sites-enabled/default contains the same information and that is the only thing I can think of?
The configuration for nginx are as in the tutorial.