9 min read
Guest

An In-Depth Guide to Deploying Node.js Apps

This in-depth guide will explore how to deploy your Node.js apps quickly and efficiently. Gain the knowledge to deploy your very own Node app!

In the world of application development, Node.js is one of the most popular and widely used tools available today. Its robust JavaScript runtime environment enables developers to easily create fast and efficient server-side applications. 

With its scalability, flexibility, and performance capabilities, it’s no wonder why so many companies are turning to Node.js for their web development needs.  

This in-depth guide will explore how to deploy your Node.js apps quickly and efficiently using best practices. By the end of this guide, you should have all the knowledge you need to get started on deploying your very own Node app! 

What Is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment enabling developers to easily create server-side applications. It’s based on Google Chrome’s V8 JavaScript engine and allows developers to build scalable network applications quickly and efficiently. 

Node.js utilizes an event-driven architecture and a nonblocking I/O model, which makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.  

What Is Deployment?

Deployment is the process of transferring a software application from its development environment to production, usually within a hosted environment such as a web server or cloud computing platform. It includes testing, installing updates, and configuring any necessary settings required for launching the application.  

Deploying an application requires comprehensive knowledge of hosting platforms and corresponding software configurations to ensure that it works properly in the designated live environment.  

Depending on their size and complexity, apps can be deployed using different methods, including manual deployments, continuous integration tools, or automated deployment scripts. 

Deploying an application requires comprehensive knowledge of hosting platforms and corresponding software configurations to ensure that it works properly in the designated live environment.

What Are the Different Ways to Deploy Node.js Apps on the Cloud?

There are several ways to deploy Node.js applications on the cloud, each with its own benefits and drawbacks.  

  • Process manager: The first option is to use PM2, an open-source production process manager explicitly designed for Node.js applications. PM2 allows developers to quickly and easily monitor and manage their applications in real time while supporting configurations such as multiple instances, hot reloading (restarting processes after changes), logging management, and more. This makes PM2 a powerful tool for quickly launching and deploying Node apps on the cloud without manually configuring or maintaining them over time. 
  • Containerization with Docker: Another way to deploy Node apps on the cloud is by using Docker containers. Docker is a popular containerization platform that enables developers to package their applications into self-contained environments called containers, which developers can easily deploy on any platform. By using Docker containers, developers can ensure that their application runs exactly how they expect it to, regardless of where it’s being deployed, while providing scalability options if needed. 
  • Serverless platforms: A third option for deploying Node apps on the cloud is using serverless cloud platforms such as AWS Lambda or Azure Functions. These platforms provide developers with an easy way to quickly spin up and run Node applications without worrying about managing servers or setting up complicated infrastructure. In addition, these services provide scalability options for efficiently handling high volumes of traffic or large datasets. 
  • Platform as a service: Developers may also opt for platform as a service (PaaS) platforms such as Heroku and Railway. With these platforms, developers don’t have to worry about managing infrastructure. Some common features of such platforms include autoscaling, logging, etc. 

This post will focus on deploying Node apps using PM2 and Docker. 

Setting Up the Node.js Application

Before we get started, it’s essential to have the setup ready, which includes the following: 

  • SSH access to the Linux virtual machine
  • Node.js and NPM installed

For the sake of this tutorial, you can use a sample Node.js todo application. First, create a folder on the VM and initialize npm.

mkdir todo-app; cd todo-app
npm init -y

Once done, let’s create the main application. Create an index.js and paste the code from the GitHub Gist. Also, install all required packages using the following command: 

npm install express body-parser helmet compression cors --save

Deploy a Node.js Application Using PM2

After installing the Node.js packages, start the Node.js app using node index.js to test the application. 

Now, it’s time to get started with the deployment. First, install PM2 using this command: 

npm i -g pm2

Now, start the application using the following command. 

pm2 start index.js --name="todo-app"

To test if the application is working, we can use the cURL command. 

curl localhost:3000/list

The output should be [“Buy Egg”]. If your output is this, you’re good to go. 

We used the cURL command to test the application locally, as we haven’t enabled public access to our application. To do that, open ports 80 and 443 from your cloud provider and enable ports 80 and 443 from the firewall. 

sudo ufw enable
sudo ufw status
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

Enabling Public Access Using NGINX

Now, it’s time to use NGINX (as Reverse Proxy) to enable internet traffic to access our application. First, install NGINX using the following command: 

sudo apt install nginx
sudo systemctl status nginx

After that, let’s update the NGINX config and restart the NGINX server to get started. Feel free to use your favorite text editor to make changes to the config file.

sudo vi /etc/nginx/sites-available/default

In the config file, you’ll find a server block (something like server {…}) and a default location block inside the server block. Remove the location / block and the following block. 

location / {
        proxy_pass http://localhost:3000; #whatever port your app runs on
        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;
}

Replace the port in the proxy_pass with the port your node application is running on. You can also add the following line in the server block (just above the location block) to map your custom domain with the public IP of your VM. 

server_name yourdomain.com www.yourdomain.com;

It’s crucial to test the NGINX config after updating the config file. Use the following command to test the NGINX config. 

sudo nginx -t

Note: If the status failed, you might have missed something when editing the server file. 

Now, restart NGINX using this command: 

sudo service nginx restart

If your application is up and running, it’s time to test public access. 

Visit your cloud provider to copy the public IP address of the VM and open it using a web browser (you can use Postman or cURL). If you get 404: Page not found, you don’t have to worry, as we don’t have any controller for the / route. 

Visit <<IP>>/list to check the output. 

The output should be [“Buy Eggs”]. You can also test the /add endpoint to add an item using the following command: 

curl -H 'Content-Type: application/json' \
      -d '{ "todo":"Go to market"}' \
      -X POST \
      http://<<IP>>/add

A dog wearing glasses

Description automatically generated with low confidence

Adding SSL Certificate

We can also add an SSL certificate to our application to make it more secure and trusted. We’ll use Certbot’s Standalone mode to get a certificate from Let’s Encrypt. 

First, let’s install Certbot to get started. The Certbot document suggests using Snap to install Certbot. 

sudo apt-get remove certbot
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
sudo certbot --nginx

We’ve first removed Certbot to ensure there are no old packages installed using other package managers. 

Then, we simply install Certbot and use the ln command to use the Certbot command. 

At last, we use the Certbot command (–nginx flag) to install the certificate. Ensure that you’ve added server_name in the server block and a record in your DNS records with the public IP of your machine before proceeding. 

Deploy a Node.js Application Using Docker

We can also run our Node.js application using Docker rather than PM2. To do that, let’s first install Docker on the VM. 

sudo snap install docker

First, stop the existing application running on port 3000 using PM2. 

pm2 stop todo-app

We can either use Dockerfile or the docker-compose.yml file to run the application. We can also use both of them together, but the application doesn’t have any integrations such as Redis, Mongo, etc., so let’s just use Dockerfile to get started. 

Create a Dockerfile and add the following code: 

touch Dockerfile

FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "index.js"]

Now, it’s time to build and run the application in detached mode. 

docker build -t myapp .
docker run -d -p 3000:3000 myapp

And we’re done. 

As we’re running the same on the same port, we don’t have to make any changes in the NGINX config. If you’ve changed the port, ensure that you’ve updated proxy_pass in the config file. 

Conclusion

In conclusion, deploying Node.js applications in production can be a daunting task if not done properly. By following the steps outlined in this post and leveraging tools such as PM2 and Docker containers, developers can rest assured that their apps are running optimally on Linux virtual machines with minimal effort required for maintenance or scaling purposes.  

For even greater ease and flexibility, consider trying Control Plane’s hybrid platform, which combines the computing power of major cloud providers and provides a global environment for building and scaling your backend services. 

Sign up now and experience worry-free Node.js app deployment!”

This post was written by Keshav Malik, a highly skilled and enthusiastic Security Engineer. Keshav has a passion for automation, hacking, and exploring different tools and technologies. With a love for finding innovative solutions to complex problems, Keshav is constantly seeking new opportunities to grow and improve as a professional. He is dedicated to staying ahead of the curve and is always on the lookout for the latest and greatest tools and technologies.