How To Install Node.js on Ubuntu: A Complete Guide
Node.JS is a sharp, light and scalable JavaScript Runtime produced on the V8 engine for Chrome. This allows developers to create effective and high-performance applications on the servers side using JavaScript. If you develop backnd logic for API, real-time webapper or even web platforms, Node.JS is a solution. In this wide guide we will run you in many ways to install node.JS on Ubuntu, as well as how to manage versions, manage test installations and handle general problems.
This guide is sewn for both beginners and advanced users, and we cover in detail how to install using Node.J:
Ubuntu standard depot
Nodesource ppa
NVM (Node Edition Manager)
Snap package
Each method has its advantages based on development needs, safety expectations and control over the version.
Why Choose Ubuntu for Node.js Development?
Ubuntu, being one of the most popular Linux distributions, is widely used for development and deployment. It offers:
-
Stable and secure LTS (Long Term Support) releases
-
Vast community support
-
Compatibility with most open-source tools and runtimes
-
Easy integration with Node.js and npm packages
Whether you’re using Ubuntu on a server (e.g., Ubuntu 22.04 LTS) or on your local machine, the steps provided here apply seamlessly.
Method 1: Install Node.js from Ubuntu Default Repository
The easiest way to install Node.js is by using Ubuntu’s built-in APT package manager. However, this method might not give you the latest version of Node.js.
Step-by-step Instructions
-
Update your package index:
-
Install Node.js and npm (Node Package Manager):
-
Verify Installation:
Check installed versions:
This method is simple but often installs an outdated version, which may not support some of the latest JavaScript features or packages. For newer versions, continue to the next method.
Method 2: Install Node.js via NodeSource PPA (Recommended)
If you need the latest stable version or even a specific version of Node.js, installing from NodeSource’s Personal Package Archive (PPA) is highly recommended.
Step-by-step Instructions
-
Update system and install curl:
-
Download and add the NodeSource PPA (replace ‘setup_18.x’ with your preferred version):
-
Install Node.js:
-
Verify the installation:
This method ensures you have the latest production-ready version and works well for both development and deployment environments.
Method 3: Install Node.js Using NVM (Node Version Manager)
NVM (Node Version Manager) is the best way to manage multiple Node.js versions on the same system. It’s ideal for developers working on multiple projects requiring different versions of Node.js.
Advantages of Using NVM
-
Install multiple Node.js versions side by side
-
Easily switch between versions
-
No need for sudo
-
Cleaner environment management
Step-by-step Instructions
-
Download and install NVM:
-
Activate NVM (for current session):
To make NVM available in all terminal sessions, you can add the above block to your .bashrc
or .zshrc
file.
-
Install latest Node.js version:
-
Install a specific version (optional):
-
Switch between versions:
-
Set default version:
-
Check installed version:
This method is highly flexible and preferred in local development environments.
Method 4: Install Node.js Using Snap Package
If you prefer using Snap, the universal Linux package system, Node.js is also available as a snap package.
Step-by-step Instructions
-
Ensure Snap is installed:
-
Install Node.js Snap:
-
Verify installation:
While convenient, the Snap version of Node.js is self-contained, which may not integrate well with system paths or custom configurations.
How To Uninstall Node.js from Ubuntu
Depending on how you installed Node.js, use the corresponding uninstall method.
Uninstall APT version:
Uninstall NodeSource version:
Uninstall Snap version:
Uninstall NVM version:
Or uninstall all versions manually from the ~/.nvm
directory.
Install npm Packages Globally Without sudo (NVM Users)
When using NVM, avoid using sudo
to install global packages. Instead, configure npm to use a directory in your home path:
Add this to your shell config (.bashrc
, .zshrc
, etc.):
Apply changes:
Now, you can safely install global packages:
Best Practices After Installation
✅ Keep Node.js and npm updated
If installed via NVM or NodeSource, you can easily upgrade to the latest version:
or
✅ Use npx
for one-off commands
npx
comes bundled with npm and allows you to run packages without globally installing them:
✅ Avoid using root for development
Always prefer user-level installs unless absolutely necessary, especially for global packages or scripts.
Setting Up a Basic Node.js Server on Ubuntu
After successfully installing Node.js, most developers move on to setting up a basic web server. Node.js makes this incredibly simple thanks to its built-in HTTP module. This section will guide you through creating a simple, functional Node.js server on your Ubuntu system.
Step-by-Step: Creating a Simple Node.js Server
-
Create a new project folder:
-
Initialize the project:
This creates a package.json
file with default values.
-
Create a server file:
-
Add the following code:
-
Run the server:
-
Test it in a browser or curl:
Open your browser and navigate to http://localhost:3000
or use:
You should see:Hello, World!
Setting Up Node.js with Express Framework
While the built-in HTTP module is great for learning, most real-world applications use Express.js, a minimalist and powerful framework for building APIs and web applications.
Install Express:
Create app.js
:
Add the following code:
app.get(‘/’, (req, res) => {
res.send(‘Welcome to your Express server!’);
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Run your Express app:
You now have a basic Express server running on Ubuntu.
Running Node.js Server in Background with PM2
For production environments, you’ll want your Node.js server to run in the background, restart automatically if it crashes, and launch on system boot. That’s where PM2, a Node process manager, becomes useful.
Install PM2 Globally:
Start your app with PM2:
Save process list and configure startup script:
This will generate a startup script you need to run (usually shown in the terminal). Once done, your app will restart automatically after a reboot.
Firewall Configuration for Node.js on Ubuntu Server
If you’re using a cloud VPS or server, make sure that the firewall allows incoming traffic on the port you’re using (e.g., 3000 or 80).
Open a port using UFW (Uncomplicated Firewall):
To check UFW status:
This ensures your app is accessible from external devices.
Setting Up Node.js with a Reverse Proxy Using Nginx
For production-grade deployments, it’s best practice to run your Node.js server behind a reverse proxy like Nginx. This offers:
-
SSL termination
-
Load balancing
-
Enhanced security
-
Better performance
Install Nginx:
Configure Nginx:
Create a new configuration file:
Add the following:
server_name your_domain.com;
location / {
proxy_pass http://localhost:3000;
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;
}
}
Enable the configuration:
Now, your Node.js app is being served via Nginx on port 80.
Final Recommendations for Ubuntu + Node.js Users
✅ Keep your system and packages up to date:
✅ Use .env
files for environment-specific variables
Install dotenv
:
Add at the top of your app.js
:
Then create a .env
file:
This is essential for managing sensitive config data.
✅ Implement Logging and Monitoring
Use libraries like:
-
Winston for logging
-
Morgan for HTTP request logging
-
New Relic or Datadog for monitoring in production
Node.js Security Best Practices on Ubuntu
Once your Node.js application is up and running on Ubuntu, securing your server and application is essential. Node.js applications are often exposed to the internet, making them vulnerable to common web attacks such as XSS, CSRF, and code injection. In this section, we outline key best practices for securing your Node.js environment on Ubuntu.
1. Avoid Running as Root
Never run your Node.js application as the root user. If a malicious actor exploits your application, they could gain full control over your system. Instead, create a new system user specifically for running your app:
Use this user to run your application or configure PM2 to do so.
2. Use HTTPS with SSL/TLS
If your app handles any sensitive data, such as login credentials or personal information, it must run over HTTPS.
You can use Let’s Encrypt to generate a free SSL certificate:
Certbot will automatically generate and renew your certificates.
3. Sanitize and Validate All Inputs
To prevent SQL injection, XSS, and NoSQL injection, always validate and sanitize inputs:
-
Use validator.js or Joi to validate user input.
-
Avoid using untrusted user input directly in queries or output.
Install validator
:
Example:
4. Keep Dependencies Up-to-date
Many vulnerabilities come from outdated npm packages. Use tools like:
To fix known vulnerabilities:
Or use:
For long-term projects, consider using npm-check-updates
:
5. Prevent Directory Traversal and Access to Sensitive Files
Always serve static files from a dedicated public directory and not from the root of your project.
Example using Express:
Ensure .env
, config files, and other sensitive files are never exposed to users.
6. Use Helmet Middleware
helmet
helps secure your app by setting various HTTP headers:
Then in your app:
This middleware protects against:
-
Cross-site scripting
-
Clickjacking
-
MIME-type sniffing
-
Other common vulnerabilities
Performance Optimization Tips for Node.js on Ubuntu
Ensuring optimal performance is crucial when deploying applications in production. Node.js is already non-blocking and efficient, but with a few tweaks, you can push its performance further.
1. Use Clustering for Multi-Core Systems
By default, Node.js runs in a single-threaded process. You can use the built-in cluster module to fork processes on multi-core systems:
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
http.createServer((req, res) => {
res.writeHead(200);
res.end(‘Handled by worker\n’);
}).listen(8000);
}
This allows your application to handle more simultaneous users.
2. Use Gzip Compression
Compress responses to reduce bandwidth usage and improve load times:
Then:
3. Enable Caching
Use tools like Redis or in-memory caching for frequently accessed data. For static files, configure Nginx to cache them for faster delivery.
4. Monitor Memory and CPU Usage
Use PM2’s built-in monitoring tools:
Or integrate tools like:
-
New Relic
-
Datadog
-
AppDynamics
To visualize performance and detect memory leaks, event loop delays, and CPU spikes.
5. Minimize Dependency Overhead
Audit your package.json
for unused or heavy packages. Uninstall any unnecessary dependencies and use lightweight alternatives wherever possible.
Deploying a Full-Stack Node.js Application on Ubuntu
After completing the setup of Node.js, you may want to deploy a full-stack application that includes:
-
Node.js (backend)
-
React/Vue/Angular (frontend)
-
MongoDB/PostgreSQL (database)
To do this efficiently:
-
Backend: Host Node.js with PM2 and Nginx.
-
Frontend: Build frontend with
npm run build
, then serve the static files from Nginx. -
Database: Install and secure MongoDB or PostgreSQL with restricted access and user roles.
-
Environment Variables: Store sensitive configs in
.env
and load viadotenv
.
Conclusion
Installing Node.JS on Ubuntu can be done in many effective ways, whether using APT depot, noderce, snap or very flexible NVM method. When established, it is necessary to establish your development environment correctly, adapt to performance and secure your app for long -term success.
Ubuntus strong ecosystem makes it ideal for running Node.JS applications in both growth and production settings. By following this guide step by step, you can ensure a stable, safe and high performance environment for your Node.JS apps.
Read More: Termux: Why Does Pandas Install Hang?