How to Deploy Node.js Application on Ubuntu 20.04

How to Deploy Node.js Application on Ubuntu 20.04. In this guide we will introduce Node.js with it’s main advantages then move onto deploying Node.js application with Nginx as a reverse proxy.

Shall we start with How to Deploy Node.js Application on Ubuntu 20.04.

What is Node.js?

Node.js is an extremely powerful open source, Javascript based platform used for developing online chat applications, video streaming sites, single page applications, and several other I/O intensive web applications and apps. Since it is built on the JavaScript V8 Engine of Google Chrome, the application is highly popular among large established companies as well as newly formed start-ups.

Moreover, it uses “Single Threaded Event Loop” architecture to handle several clients at the same time. Hence, it is one of the most suitable and efficient platforms for real time applications.

If you use Node.js for developing web applications, you tend to acquire the following features:

  • Asynchronous And Event Driven – The APIs included in a Node.js library are asynchronous or non blocking. Means that its server never waits for an API to return data. Instead, it moves to another API after calling it. Gets help from the notification mechanism of events.
  • Effortless – The application is quite effortless to begin with. Web developers usually choose this platform as it provides several tutorials and a large community to help them deal with it.
  • Single Threaded Yet Highly Scalable – As discussed above, Node.js uses a Single Threaded model with event looping. With the help of the event mechanism, the server acquires the response from the API in a non blocking manner, thereby making it highly scalable. This program also provides service to a large number of requests.
  • PackagesNode.js provides a variety of packages to simplify the work.
  • No Buffering – The application never buffers any data. Instead, it outputs the data in lumps.
  • Sturdy Backend – Since the application is written in C and C++, it provides features like networking support and is relatively fast.
  • Maintainable – Web Developers love to use Node.js since both the front end and backend are managed with JavaScript as the single language.

Advantages of Node.js

The advantages of Node.js are as follows:

Provides High Performance For Real Time Applications

Also Node.js enables you to build applications that provide results in just a matter of seconds. Applications powered by this platform are highly capable of multi tasking. Its single threaded, event driven architecture processes several parallel requests efficiently without jamming the RAM. Further, its event loop or non blocking I/O operations allows you to execute code in a way that indirectly affects the application’s overall performance.

Easily Scalable

You can scale the application effortlessly in any direction. While it can be scaled horizontally by adding nodes to the existing system, you can scale vertically by adding additional resources to the single nodes. Therefore, it is highly scalable and efficient compared to other JavaScript servers.

Powerful Data Processing

The platform uses a backend development language and runtime environment, which makes it highly capable of processing multiple requests simultaneously. Because of that it is considered the perfect option for efficient data handling tools.

Cost Efficient

You can write server side code in JavaScript alongside JavaScript code on the front end effortlessly. Therefore, when you think of hiring a block of two resource teams, you tend to save a great deal of time, cost and energy for overall project development.

Provides Benefit Of Caching

Additionally Node.js uses an open source runtime environment that provides the facility of caching single modules. So, whenever it gets a request for the first module, it is cached in application memory. You do not have to re execute the code since it will help the application load web pages faster and respond more rapidly to the users.

Follow this post and we will show you how to deploy Node.js application on Ubuntu 20.04.

How to Deploy Node.js Application on Ubuntu 20.04

Prerequisites

  • A server running Ubuntu 20.04.
  • A root user or a user with sudo privileges.

Install Node.js

By default, the latest version of Node.js is not included in the Ubuntu default repository. So you will need to install it from the Node Source repository. First, install the required dependencies using the following command:

				
					apt install apt-transport-https ca-certificates curl software-properties-common build-essential -y
				
			

Once all the required dependencies are installed, add the Node Source repository with the following command:

				
					curl -sL https://deb.nodesource.com/setup_18.x | bash -
				
			

Once the repository is added to the APT, update the repository cache with the following command:

				
					apt update -y
				
			

Once the repository is updated, you can install the Node.js package using the following command:

				
					apt install nodejs -y
				
			

After the installation, verify the Node.js version using the following command:

				
					node -v
				
			

You should see the following output:

				
					v18.7.0
				
			

You can also see the NPM version using the following command:

				
					npm -v
				
			

You should see the following output:

				
					8.15.0
				
			

Create a Node.js Application

At this point Node.js package is installed on your system. Now, its time to create a simple Node.js application and test it.

First, create a directory to hold the Node.js application with the following command:

				
					mkdir nodeapp
				
			

Then create a simple hello.js application inside the nodeapp directory:

				
					nano nodeapp/hello.js
				
			

Add the following code:

				
					const http = require('http');
const hostname = 'localhost';
const port = 8080;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('This my first Node.js Application!\n');
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

				
			

Save and close the file when you are finished, then navigate to the nodeapp directory and run your Node.js application using the following command:

				
					cd nodeapp
node hello.js

				
			

If the application runs successfully, you will get the following output:

				
					Server running at http://localhost:8080/
				
			

Press the CTRL + C to close the application. We will create a systemd file to run the Node.js application.

Create a Systemd Service File for Node.js Application

For the production environment, it is recommended to create a systemd service file to manage the Node.js application via systemctl.

To do so, create a systemd service file for Node.js:

				
					nano /lib/systemd/system/app.service
				
			

Add the following lines:

				
					[Unit]
Description=Node.js Application
After=syslog.target network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root/nodeapp
Environment=NODE_ENV=production
ExecStart=/usr/bin/node hello.js

Restart=always

[Install]
WantedBy=multi-user.target
				
			

Save and close the file when you are finished. Then, reload the systemd daemon with the following command:

				
					systemctl daemon-reload
				
			

Next, start the Node.js service and enable it to start at system reboot:

				
					systemctl start app.service
systemctl enable app.service
				
			

You can check the status of the Node.js service with the following command:

				
					systemctl status app.service
				
			

You should see the following output:

				
					● app.service - Node.js Application
     Loaded: loaded (/lib/systemd/system/app.service; disabled; vendor preset: enabled)
     Active: active (running) since Thu 2022-07-28 07:16:50 UTC; 5s ago
   Main PID: 14728 (node)
      Tasks: 11 (limit: 2347)
     Memory: 11.2M
     CGroup: /system.slice/app.service
             └─14728 /usr/bin/node hello.js

Jul 28 07:16:50 linux systemd[1]: Started Node.js Application.
Jul 28 07:16:50 linux node[14728]: Server running at http://localhost:8080/

				
			

At this point, the Node.js application service is started and listens on port 8080. You can now proceed to configure Nginx as a reverse proxy to serve Node.js application.

Configure Nginx as a Reverse Proxy for Node.js

So what is next, you will need to configure Nginx as a reverse proxy to access Node.js application on port 80. Firstly, install the Nginx web server package with the following command:

				
					apt install nginx -y
				
			

Then you will need to create an Nginx virtual host configuration file to host Node.js application. You can create it inside the Nginx configuration directory using your favourite editor:

				
					nano /etc/nginx/conf.d/nodejs.conf
				
			

Add the following configuration:

				
					server {

        listen 80;
        server_name node.example.com;
    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;
    }
}

				
			

Save and close the file when you are done,  then verify the Nginx configuration for any syntax error with the following command:

				
					nginx -t
				
			

If everything is fine, you should see the following output:

				
					nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
				
			

Restart the Nginx service to apply the configuration changes:

				
					systemctl restart nginx
				
			

You can also check the Nginx status with the following command:

				
					systemctl status nginx
				
			

You should see the following output:

				
					● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Wed 2022-06-30 11:58:13 UTC; 59s ago
       Docs: man:nginx(8)
    Process: 40436 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 40437 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 40520 (nginx)
      Tasks: 3 (limit: 4679)
     Memory: 3.2M
        CPU: 56ms
     CGroup: /system.slice/nginx.service
             ├─40520 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             ├─40522 nginx: worker process
             └─40523 nginx: worker process

July 30 11:58:13 ubuntu2004 systemd[1]: Starting A high performance web server and a reverse proxy server...
July 30 11:58:13 ubuntu2004 systemd[1]: Started A high performance web server and a reverse proxy server.

				
			

At this point, the Nginx web server is configured as a reverse proxy for Node.js application. You can now access the Node.js application in the next step.

Access Node.js Application

Now, open your web browser and access the Node.js application using the URL http://node.example.com. You should see your Node.js application on the following screen:

Thank you for your time in reading through how to Deploy Node.js Application on Ubuntu 20.04

How to Deploy Node.js Application on Ubuntu 20.04 Conclusion

In this post, we explained how to deploy Node.js application on Ubuntu 20.04. We have also installed Nginx and configured it as a reverse proxy for the Node.js application. Thousands of developers around the world use this platform due to its efficient performance. It provides a plethora of advantages to them, thereby becoming a perfect choice in comparison to other server side platforms like Java or PHP.

Take a look at our content about Node.js here.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x