Introduction
Did you know?
Node.js's market share has recently increased from 0.803% to 1.249% across all websites—a growth of 0.446 percentage points—surpassing many other backend technologies.
It’s clear that Node.js has landed itself as an important technology in the digital world. It has become essential for modern web development, offering a robust and flexible solution for building efficient backend applications. This rising popularity highlights the importance of a solid foundation for running and managing Node.js applications, particularly in production environments.
And when it comes to Node.js, setting up its server on Ubuntu 24.04 is crucial for DevOps engineers, ensuring deployment stability and efficiency. With Ubuntu's reliability, strong community support, and efficient package management, it becomes an ideal environment for hosting Node.js, particularly in production environments where stability and security are paramount.
In this article, we will be offering a step-by-step guide to set up a Node.js backend server on Ubuntu 24.04, covering installation, configuration, and optimisation to help you create a secure, production-ready server.
Let’s begin!
Prerequisites
Before diving in, meet the following prerequisites to successfully set up your Node.js server.
An Ubuntu 24.04 server
You require access to an Ubuntu 24.04 server, whether physical or virtual, because it includes the most recent LTS (Long-Term Support) features, ensuring server stability and security. This version also includes the most recent software and performance enhancements, making it ideal for modern development requirements.
Root or user access with sudo privileges
You need root access or a user account with sudo privileges to install and configure the necessary software. This level of access is required to manage software installations and make system-level changes.
Basic familiarity with the Linux command line
Understanding the Linux command line is crucial for navigating directories, editing configuration files, and installing packages efficiently.
Steps to set up Node.JS Backend Server on Ubuntu 24.04
Setting up a Node.js backend server on Ubuntu 24.04 involves several crucial steps. So, let’s understand each step in detail.
Step 1: Update Your System
Before installing any new software, you should update your system's package index to ensure you have the most recent versions of the software and security patches. Open your terminal and execute the following commands.
Note: Using "&&" ensures that the upgrade command only runs if the update is successful.
Updating your server ensures packages are current, reducing compatibility issues during Node.js installation. This is a critical step because outdated packages can cause unexpected errors and security risks. Keeping your system up to date improves the overall stability and performance of your server.
Step 2: Install Node.js and npm
Node.js and npm are essential tools for backend development. You will install both using the NodeSource repository, which contains the latest stable versions of Node.js.
First, add the NodeSource repository for Node.js version 18.x
This command downloads and runs a script that sets up the NodeSource repository on your system, allowing you to easily install and update Node.js.
Next, install Node.js and npm:
Once the installation is complete, verify it by checking the installed versions:
npm -v
These commands should display the current versions of Node.js and npm, confirming a successful installation. If the versions are incorrect or not displayed, it indicates an issue with the installation or the system path configuration.
Step 3: Setting Up a Basic Node.js App
Now that Node.js is installed, it is time to build a basic application. Begin by setting up a new directory for your project by using this command:
cd my-node-app
Next, create a new Node.js project. This will generate a package.json file to manage your project's dependencies and configurations:
Now, create a file called app.js:
This file will contain the code to start a basic HTTP server. Copy and paste the following code into app.js:
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, () => {
console.log(Server running at http://localhost:${port}/);
});
This code snippet creates a simple HTTP server that listens on port 3000 and responds to all incoming requests with "Hello World."
To run the server, execute the following command:
Step 4: Set Up Apache as a Reverse Proxy
Using Apache as a reverse proxy allows you to redirect client requests to your Node.js application. This setup enhances security and improves performance by managing incoming traffic.
Install Apache
You can use the following command to install Apache:
After installation, enable the necessary Apache proxy modules:
sudo a2enmod proxy_http
These commands activate the proxy modules, allowing Apache to forward requests to your Node.js application.
Configure Apache for Node.js
Next, create a new virtual host configuration file for your Node.js application:
To set up the reverse proxy, add the following configuration:
ServerName example.com
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
</VirtualHost>
Save and close the file, and then activate the site configuration:
To implement the changes, restart Apache:
Step 5: Enable Firewall Access
If you have a firewall on your Ubuntu server, you must grant Apache and Node.js access. In order to do so, execute the following commands:
sudo ufw allow 3000
These commands ensure that traffic flows to your server on the specified ports, allowing users to access your Node.js application via Apache. "Apache Full" enables access on both ports 80 and 443, covering HTTP and HTTPS traffic.
Step 6: Manage Your Node.js App with PM2
To ensure your Node.js application continues to run smoothly even after the system reboots or crashes, use PM2 as a process manager. PM2 allows you to easily manage your Node.js applications, ensuring they are always online.
Install PM2 Globally
To install PM2 globally, execute the following command:
sudo npm install -g pm2
Once installed, you can run your application using PM2:
This command starts your Node.js application in the background. PM2 will manage the process, allowing it to run independently of your terminal session.
TYou can monitor your application with the command:
Save the Process List
To ensure that your application begins automatically after a system reboot, save the process list:
To set up PM2 to run on startup, execute:
This command generates a command that you must execute to configure the system to start PM2 on boot. This ensures that your Node.js application will automatically restart after a reboot, improving reliability
Step 7: Test Your Node.js Backend Server
Once you have set up your Node.js backend server, you must test its functionality to ensure that everything works properly. There are several methods for thoroughly testing your server. Let’s understand them below:
#1. Testing the HTTP Server with Curl
The simplest way to test your Node.js server is by using curl, a command-line tool for making HTTP requests. Open a new terminal window and execute the following command:
If everything is properly set up, you should see the following response:
This confirms that your Node.js server is active and responding to requests.
Error Detection
If you do not receive the expected response, check that the server is operational. Ensure you start the server using node app.js and that there are no error messages in the console. Additionally, verify that port 3000 is not blocked by any firewall or already in use by another service.
#2. Using Postman for API Testing
Postman is a popular API testing tool that provides a more user-friendly interface for making requests and examining responses. To test your Node.js server, follow these steps:
- If you have not downloaded it, install Postman.
- Open Postman and initiate a new GET request.
- Set the request URL to http://localhost:3000 and click Send.
The "Hello World" response should appear in the Postman interface, similar to what you would get with curl.
Error Detection
If you do not see the expected response, check your server logs for any error messages. Make sure your Node.js server is running, and confirm that you have the correct URL and method selected in Postman.
#3. Creating Automated Tests with Mocha
Consider using a testing framework like Mocha in addition to Chai for assertions to create a more robust testing strategy. You can create unit tests to validate your server's functionality.
First, install Mocha and Chai:
Next, create a test file named test.js:
const chai = require('chai');
const expect = chai.expect;
describe('Node.js Server', function() {
it('should respond with Hello World', function(done) {
http.get('http://localhost:3000', function(res) {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
expect(data).to.equal('Hello World\n');
done();
});
});
});
});
Run the tests with this command:
Error Detection
If the test fails, check the response data logged in the console to identify any discrepancies. Common issues could include typos in the expected response or the server not running correctly. Ensure your server is active and responding as expected before running the tests.
Step 8: Troubleshoot and Debug Your Node.js Backend Server
Even with a well-established server, problems can arise. Here are some common troubleshooting and debugging strategies to help you solve problems efficiently.
a) Checking Server Logs
When something goes wrong, one of the first things to check is the server logs. To view logs for a Node.js application running with PM2, use the following command:
This command shows your application's output, including any errors or exceptions that may have occurred. Checking the logs is critical for diagnosing problems because they can provide detailed error messages explaining what went wrong and where to look for a solution.
b) Verifying Apache Configuration
If Apache is not correctly routing requests to your Node.js server, double-check your Apache configuration file located at /etc/apache2/sites-available/my-node-app.conf.
Ensure that:
- The ServerName directive is correctly set to your domain or IP address.
- The ProxyPass and ProxyPassReverse directives point to the correct port (3000 in this case).
- The necessary proxy modules (Proxy and proxy_http) are enabled.
Note: Remember to restart Apache after making any changes:
Restarting Apache ensures that any configuration changes are applied. If these configurations are incorrect, Apache may fail to route traffic to your Node.js application, resulting in errors when you try to access it.
c) Firewall Rules
If you are unable to access your application via the web, check that your firewall settings allow traffic through the required ports. To list the current UFW (Uncomplicated Firewall) rules, use:
If Apache or port 3000 are not listed, allow traffic:
sudo ufw allow 3000
Having the right firewall rules in place is critical for web accessibility. If the firewall blocks incoming traffic on the required ports, users will be unable to access your application, resulting in connection errors.
d) Debugging Node.js Application
If your Node.js application is generating errors, consider using the built-in debugger. You can launch your app in debug mode with the following command:
This command allows you to set breakpoints, step through code, and inspect variables to identify the source of any issues. Using a debugger is an effective way to troubleshoot logic errors or unexpected behaviour in your code.
e) Common Error Codes
Familiarise yourself with common HTTP error codes and their definitions. Here are a few:
- 404 Not Found: The requested resource is not available on the server. Verify the URL you provided.
- 500 Internal Server Error: An unexpected condition occurred. Check your server's logs for stack traces and error messages.
- 502 Bad Gateway: Your Node.js application is unable to communicate with Apache. Make sure your app is running and listening on the expected port.
Understanding these error codes is important for quickly diagnosing problems. Each code shows a specific problem, helping you narrow down potential causes and find effective solutions. By using these troubleshooting methods, you can diagnose and fix issues with your Node.js backend server efficiently, ensuring it runs smoothly and reliably.
How does MeisterIT Systems help in building a Node.JS backend server on Ubuntu 24.04?
At MeisterIT Systems, we provide end-to-end assistance for building a Node.js backend server on Ubuntu 24.04. We guide businesses through every step of the server setup process, from initial configuration to final deployment, ensuring a stable and efficient server environment. We also assist you in troubleshooting issues and maintaining a high-performance Node.js server. Whether you require installation, configuration, or optimisation assistance, count on MeisterIT Systems to personalise your server setup experience, making it smooth and reliable.
Conclusion
Setting up a Node.js backend server on Ubuntu 24.04 involves several crucial steps, including system updates, Node.js installation, configuring Apache as a reverse proxy, and managing processes with PM2. Following this guide enables DevOps engineers to construct a secure and scalable backend environment, guaranteeing optimal performance and uptime.
MeisterIT Systems offers comprehensive technical and troubleshooting support for each phase of server setup, assisting businesses in achieving robust and efficient Node.js deployments. Whether you're eager to begin or require guidance at any point, connect with us to ensure your Node.js journey is smooth and successful.
Frequently Asked Questions
How can I install Node.js on Ubuntu 24.04?
To install Node.js on Ubuntu 24.04, add the NodeSource repository and then run sudo apt install -y nodejs. This command installs Node.js and npm, which allows you to easily run backend applications.
Why use Apache as a reverse proxy for Node.js?
Apache functions as a reverse proxy, enhancing security, performance, and scalability. It manages incoming traffic and routes it to your Node.js server, improving load balancing and preventing the Node.js app from being directly exposed to the internet.
Are ERP or CRM systems only for large enterprises, or can small businesses benefit too?
PM2 is a process manager for Node.js that keeps your application running even after crashes or system reboots. It also includes monitoring and automatic restart capabilities, which are critical for ensuring application stability in production environments.
How do I troubleshoot my Node.js server?
To troubleshoot Node.js issues, check server logs (pm2 logs), verify Apache configurations, ensure correct firewall settings, and use tools such as the Node.js debugger. Analysing error messages allows you to effectively identify and resolve specific problems.