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.
This guide assumes that you have the following:
sudo
privileges, as described in the initial server setup guide for Ubuntu 16.04.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.
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:
You can inspect the contents of this script with nano
(or your preferred text editor):
Then run the script under sudo
:
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:
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:
The Node.js runtime is now installed, and ready to run an application. Let’s write 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.
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
:
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):
#!/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.
In order to test your application, set hello.js
to be executable using chmod
:
Then run it like so:
OutputServer 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
:
If you see the following output, the application is working properly and listening on the proper address and port:
OutputHello 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.
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:
The -g
option tells npm
to install the module globally, so that it’s available system-wide.
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[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:
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):
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
:
For a detailed overview of systemd, see Systemd Essentials: Working with Services, Units, and the Journal.
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 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:
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.
. . .
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
:
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:
Next, 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).
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.
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!
should be change to
?
I actually didn’t have much luck with
pm2 startup ubuntu
, whilepm2 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:
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:
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 inhttp { }
. 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
The example here expects that
/etc/nginx/nginx.conf
contains a section like so:…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
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:
and get this:
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:
use:
Also I had error after ./letsencrypt-auto certonly --standalone
In my case, before running letsencrypt-auto:
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
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
to
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 typingsudo 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
So logging in as another user and running all the commands with sudo would have the same effect? Everything’s in the same place?
Yes! Although not all commands need to be run as superuser
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:
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.
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:
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.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 in400 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;
to
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:
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.
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:
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.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 in400 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;
to
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:
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.
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:
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.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 in400 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;
to
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.
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?
Turns out, there was a temporary file named
default~
created by emacs in the same directory that was causing the problem. Simply remove the temp file and the error will go away.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:
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?
I struggled with this for over an hour! It turns out I was SSHing into my server using my ip address while I had configured my site to use a domain name. The minute I SSHd into my server using my domain name, everything worked.
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:
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:
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:
Add the following to your configuration:
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.Great tutorial!
I want to try out the nginx function, config my
location
block tolocation /app2 { ... }
, then browse my website bydomain.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.
requires a dump of the running process list to be saved using
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!
It would be nice to have some reference to the tutorial about setting up server blocks. I’m using nginx as a reverse proxy so I can run several websites from one droplet. Adding something like: "if you have set up multiple server block virtual hosts you can replace the location block in each file created in the sites-available directory with
Be sure to change
8080
to the port of each node processWhy
pm2
? Any chances to useforever
?how to setup server blocks with nodejs app as root with wordpress as child?
location /{ }
location /blog{ }
tnx…x :|
should “https://deb.nodesource.com/setup_6.x” now be updated to “https://deb.nodesource.com/setup_9.x” ? 6.x is no longer the newest version of node
I absolutely cannot get this code to work. I literally followed the whole tutorial step-by-step, and after adding this “hello.js” file and making it executable, it simply doesn’t work. It starts up and displays the console log, but when I try to visit it (or curl it) it doesn’t load.
Any idea? I’ve been at this for the past two hours and I’m about to go insane.
Hi, Thanks for the great tutorial. I tried to add a second location block as follow
However, the app only works for the 1st location ( location / ). It doesn’t work for the ( location /test ), although it refers to the same app running at port 8081. Does anybody know what is the problem?
The app is actually a node.js. Does it have anything to do with node.js configuration?
Your tutorial is awesome! Thank you for helping us!
To deploy the easy way with a single command to your digitalocean droplet, you could use a tool like OpsCaptain. OpsCaptain brings the PaaS experience to your own server. No need to fiddle with bash scripts and maintain them. Simply connect your droplet and upload your project from the dashboard or run [opscaptain deploy]. It is that easy to deploy to your droplet. https://www.opscaptain.com/nodejs-hosting
This just doesn’t work. No change after modifying location.
Hello,
I followed the tutorial and it works, but I need to configure the server to run a Nuxt.js app. On their website there are instructions for something I think is to be put in /etc/nginx/sites-available/… (https://nuxtjs.org/faq/nginx-proxy/). However I do not understand what is the addres of the Node.js instance to substitute.
Moreover I was wondering: why would I want to use Nginx as a proxy? Cannot I just upload my app in the /var/www/html folder?
Sorry if I am saying stupid things, I am a beginner… :-)
502 Bad Gateway
This comment has been deleted
This comment has been deleted
I tried with
pm2 startup systemd
and then executed the command as in the outputsudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u user --hp /home/user
I encountered the following error.
How to solve this?
System = Ubuntu 16.04 x64
Great article, I am looking for some steps to deploy the releases on a daily basis. How do i do it what are the steps to follow.
And if you can the best practices that would be great.
thank you vary much , this tutorial is very easy to a newer to learn ,这个网站的很多教程都写的非常棒!hope one day i can give a tutorial like this .
Thanks for such a great blog. PM2 is marvellous. my sockets use to hang up for some reason and node went down. PM2 takes care of that. Can you tell me where I can see the logs? I have a few console.log I would like to track. It would be nice to reset the logs every 24 hours as well. thanks
nevermind, I got it from running pm2 info app. how to limit the size of log files though?
please add info about doing a proxy with socket.io included!
I am trying to run two different apps in the same server but with no success. The two apps use Express and Node.js, here is what I’ve tried so far: location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. proxy_pass http://localhost:4001; 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; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } location /angry-pigs { rewrite /angry-pigs/(.*)$ /$1 break; proxy_pass http://localhost:5010; proxy_http_version 1.1; proxy_set_header Upgrage $http_upgrade; proxy_set_header Connection ‘upgrade’; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; }
I was receiving 404 errors until I appended a
/
after the proxy_pass value.if the application code is on my local machine, how do I copy it to the digital ocean sever ? which folder should it be copied to ?
Hi, I’m hoping someone can help me figure out why part of this tutorial isn’t working for me. I’m following along with an Express app I’ve already built instead of the example Node app. Everything is working correctly until I run the long command to start the pm2 process on reboot. After doing so, when I run this command:
It says the process is Loaded but that it’s Inactive (Dead).
If anyone could help me figure out why this is happening, I would really appreciate it. The app is working correctly both if I just run it with nodejs and if I run it in the background with pm2. I just want to ensure it starts back up if the server reboots.
While checking in browser of my local machine, i am getting error like connection refused
need update for ES6 with PM2.
Big thanks for this post!
I would just add that after “Note: When installing from the NodeSource PPA, the Node.js executable is called nodejs, rather than node.”
It is necessary to create a simlink: ln -s /usr/bin/nodejs /usr/bin/node
When I followed the tutorial, PM2 complained about “node” executable name. I solved the issue with the simlink.
In case the react app has react router. How will the config file change for router to work because this configuration doesnot seem to work with react router it would give 404 on react routes.
The curl node command
curl -sL https://deb.nodesource.com/setup_6.x -o nodesource_setup.sh
is deprecated and you should visit node.js distributions page for latest distributions.Hi, In my web app, I’m not using nodejs as shown here as a proxy listening on a port. I have an html file that in one of its <script> tags refers to a js file that I’ve compile using npx from a javascript file before. how can I put my web app on my domain in digital ocean then? thanks in advance
Is this still all up to date to work with Ubuntu 20.04 ?