Node.js remains the backbone of modern web applications, powering heavy-duty APIs, microservices, and server-side rendering engines. If you are configuring a fresh Ubuntu server or setting up a local dev machine, installing Node.js is often your first step.
To install Node.js on Ubuntu quickly, use the command sudo apt install nodejs npm. However, for production servers or multi-project setups, developers prefer using NVM (Node Version Manager) or the NodeSource PPA to manage specific, up-to-date LTS versions without encountering permission bugs.
Choosing the right installation path depends entirely on your target environment. Use this quick comparison matrix to determine which method aligns best with your architecture:
| Installation Method | Difficulty | Version Flexibility | Production Suitability | Best Use Case |
|---|---|---|---|---|
| Ubuntu APT Repository | Easy | Very Low (Fixed Version) | Moderate | Quick tests, small microservices, and basic local scripts. |
| NodeSource PPA | Moderate | High (Specific LTS/Current) | High | Standard production servers, Dockerfiles, and CI/CD pipelines. |
| Node Version Manager (NVM) | Moderate | Outstanding (Switch on the fly) | High (For single tenants) | Development laptops, staging environments, and multi-app environments. |
Need an isolated sandbox to test this setup? Spin up a root-access VPS in seconds with an InterData High-Performance VPS starting at competitive local rates.
Preparing Your Ubuntu Server (Prerequisites)
Before installing Node.js, your Ubuntu system requires an active non-root user with sudo privileges, an updated package registry, and essential development tools. Preparing your system prevents package resolution conflicts and permission errors during dependency installation.
When setting up a public-facing virtual private server (VPS), working directly under the root user profile is a notable security risk. A simple typo or an exploit inside an installed NPM dependency could grant an attacker complete control over your operating system. Using a standard user with escalated sudo privileges isolates system operations.
Run the following commands to update your package indexing files and bring all existing packages to their newest releases:
sudo apt update && sudo apt upgrade -y
Once the repository definitions are updated, you should install several development dependencies. Many popular modern npm utilities compile native C++ add-ons using a tool called node-gyp. Without a functional compiler setup, complex node packages will throw compilation errors during the npm install phase.
Install the required compile tools and downloading utilities by executing:
sudo apt install build-essential curl -y
With your base package manager refreshed and critical build tools in place, your Ubuntu server is ready to host a runtime instance of Node.js.
Method 1: The Stable Way (Using the Ubuntu APT Repository)
Installing Node.js via Ubuntu’s default APT package manager is the easiest route for quick tests or running basic microservices. While stable, this method usually provides an older LTS version curated by the canonical Ubuntu team rather than the latest upstream release.
For straightforward servers or background utilities that do not require modern runtime optimizations, using the official OS repository keeps your server maintenance incredibly simple.
To execute a clean install using the standard system repositories, run the following command:
sudo apt install nodejs npm -y
Once installed, check where the binaries are located on your disk and confirm that the execution paths are configured correctly:
which node
# Output: /usr/bin/node
which npm
# Output: /usr/bin/npm
The Reality Check: Why This Method Falls Short
While the ease of standard APT installation is attractive, it often leads to frustration for modern full-stack developers. Ubuntu package maintainers prioritize system stability over publishing fast-moving software cycles.
As a result, the Node.js version provided in standard repositories can lag significantly behind the current ecosystem standards. In 2026, building on newer application frameworks like Next.js or Astro requires at least Node.js 22 LTS or Node.js 24 LTS. Using an older Node.js runtime causes immediately broken deployments, syntax failures on modern features (such as standard Fetch APIs or ES Modules), and package manager lock conflicts.
Method 2: The Production Standard (Using NodeSource PPA)
The NodeSource PPA (Personal Package Archive) is the recommended installation method for production Ubuntu servers. It injects official Node.js binaries directly into your APT manager, allowing you to deploy specific LTS or Current versions (like Node 22 or 24) with automatic security updates.
Using NodeSource provides the speed and reliability of upstream distributions while retaining standard apt-get command syntax for management.
Historically, configuring NodeSource involved piping raw remote scripts directly into bash commands (curl ... | sudo bash -). Modern system security standards discourage this practice. In 2026, we utilize the modern Debian source configuration format, integrating keys into /etc/apt/keyrings.
Follow these structured commands to register and install a specific target version of Node.js. In this example, we configure Node.js v22 LTS (Codename Jod):
First, establish a dynamic shell variable for your chosen major Node.js release:
NODE_MAJOR=22
Now, download the GPG security key from the NodeSource team, securely import it to your system keyrings directory, and establish an explicit apt source definition file:
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo mkdir -p /etc/apt/keyrings
# Fetch the GPG key and convert it to a binary keyring format
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
# Create an entries list mapping directly to the target major repository
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
With the new source map assigned, update your local packages metadata to index the new repository and run the installation:
sudo apt-get update
sudo apt-get install nodejs -y
┌──────────────────────────────────────────────┐
│ Ubuntu System package manager │
└──────────────────────┬───────────────────────┘
│ Retrieves definitions
▼
┌──────────────────────────────────────────────┐
│ /etc/apt/sources.list.d/ │
│ ► points to official NodeSource mirrors │
└──────────────────────┬───────────────────────┘
│ Updates package pool
▼
┌──────────────────────────────────────────────┐
│ Node.js Runtime & NPM Bundled │
│ ► Single dependency deployment │
└──────────────────────────────────────────────┘
When you use the NodeSource PPA approach, the nodejs package is consolidated. This means that both the executable execution paths and the corresponding npm packages are integrated directly into a singular native configuration, avoiding version mismatches during deployment.
Method 3: The Developer-First Way (Using NVM - Node Version Manager)
Node Version Manager (NVM) is the best choice for development machines and active testing servers. It operates at the user profile level, enabling you to install, switch, and run multiple Node.js versions concurrently on the same Ubuntu instance without using sudo.
This setup is ideal for testing code across multiple execution engines or running distinct software configurations simultaneously on a single instance.
Step 1: Downloading the Setup Script
To pull down the latest stable edition of NVM (currently at v0.40.4), run the following network pull via curl:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.4/install.sh | bash
Step 2: Refreshing the Environment Paths
The installation utility writes path modification lines directly to your active shell configuration profile (such as ~/.bashrc, ~/.profile, or ~/.zshrc). Rather than terminating and spawning a new terminal pane, apply these terminal path adjustments directly to your active pane:
source ~/.bashrc
Verify that the version manager is registered properly:
nvm --version
# Output: 0.40.4
Step 3: Installing and Switching Node Versions
Now you can install the exact versions of Node.js required for your applications. To install Node.js 22 LTS and Node.js 24 LTS, run the following commands:
# Deploy latest Node 22 LTS
nvm install 22
# Deploy latest Node 24 LTS
nvm install 24
To view all active installations on this user profile:
nvm ls
If you are working on a project built on an older codebase that fails on newer Node versions, you can switch back to an older runtime seamlessly.
For instance, to run a server with Node 22:
nvm use 22
To switch to Node 24 for a modern API service:
nvm use 24
To set Node.js 24 as your global default for any new terminal session:
nvm alias default 24
Because NVM executes entirely inside the user home folder profile path (~/.nvm), installing global packages never requires administrator permissions, keeping your environment organized and secure.
Post-Installation: Verification & Global NPM Best Practices
After installation, you must verify your active binary versions and configure your global NPM directory path. Fixing global directory access ensures you can install packages like pm2 or nodemon globally without getting persistent EACCES permission errors.
Begin by confirming the operating versions of both key packages:
node -v
# Example Output: v24.2.0
npm -v
# Example Output: 10.8.2
Pro-Tip: Fixing the Global Permissions Trap
When using APT or NodeSource methods, standard directory configurations map the global NPM installation space to system locations like /usr/lib/node_modules. If you try to run commands like npm install -g pm2, Ubuntu will abort with an EACCES: permission denied message.
You can resolve this by remapping the global module path directory straight to your user space (~/.npm-global). This approach isolates global packages from the core operating system, eliminating the need for sudo and preventing permission conflicts.
Run these setup commands to configure the custom local path:
# Create directory for global NPM packages
mkdir ~/.npm-global
# Reconfigure NPM to write global installations to the new directory
npm config set prefix '~/.npm-global'
Next, open your shell profile configuration (~/.bashrc) in your preferred text editor:
nano ~/.bashrc
Add the following path injection block to the very bottom of the file:
export PATH=~/.npm-global/bin:$PATH
Save and exit the file (in nano, press Ctrl+O, Enter, then Ctrl+X). Apply your configuration adjustments immediately:
source ~/.bashrc
Now, you can install any global CLI module without prefixing administrative sudo instructions:
npm install -g pm2 nodemon
Security & Production Optimizations on VPS Environments
Running Node.js apps on a live VPS requires strict system-level isolation, reverse proxying, and daemonization. Never run Node.js on port 80 or 443 directly; instead, bind it to localhost and route traffic through Nginx while managing the process with PM2.
┌──────────────────────┐
│ Incoming Traffic │
│ (Port 80 / 443) │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Nginx Proxy │
└──────────┬───────────┘
│ Forwarding
▼ (Internal Port 3000)
┌──────────────────────┐
│ PM2 Node Process │
└──────────────────────┘
1. Keep App Services Active with PM2
Node.js processes run as single-threaded scripts. If an uncaught exception triggers an error within your application loop, the execution thread halts, crashing your server.
Using the PM2 Process Manager keeps your app running continuously. PM2 monitors execution and automatically restarts your node application if it crashes or if the host machine reboots.
Navigate to your application root directory and initialize the process under PM2:
# Launch app.js with a custom application identifier
pm2 start app.js --name "production-api"
To ensure PM2 starts your application automatically after a system reboot, generate a startup script configuration:
pm2 startup systemd
Copy the command output displayed on your terminal and run it with root privileges. Once authorized, save your active processes list:
pm2 save
2. Configure an Nginx Reverse Proxy
While you can run your Node.js application directly on port 80 or 443, doing so is highly discouraged. It forces your app process to run under elevated root authority, exposing your host systems to security vulnerabilities. Instead, bind Node to localhost and route traffic through an Nginx proxy.
First, install Nginx:
sudo apt install nginx -y
Next, open the default configuration block file:
sudo nano /etc/nginx/sites-available/default
Modify the location context structure under the primary server directive. Adjust the configuration to match this block:
server {
listen 80;
server_name yourdomain.com; # Or your server's IP address
location / {
proxy_pass http://127.0.0.1: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;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Verify your Nginx configuration for syntax errors:
sudo nginx -t
If the test is successful, reload the Nginx daemon to apply your changes:
sudo systemctl reload nginx
3. Resource Monitoring on Entry-Level VPS Environments
When hosting multiple applications on entry-level cloud nodes, monitoring memory usage is essential. You can track resource consumption in real-time using PM2's terminal interface:
pm2 monit
Alternatively, configure memory-based auto-restarts within PM2 to prevent memory leaks from crashing your server:
pm2 start app.js --max-memory-restart 300M
💻 Deploying Your Production App? Node.js applications demand low latency and high physical I/O speeds. If your app is bottlenecked by CPU or disk speed, migrate to a dedicated, high-speed InterData VPS. Get ultra-fast NVMe storage, unshared CPU cores, and stellar uptime guarantees for your Node projects.
Troubleshooting Common Ubuntu Node.js Roadblocks
This section covers standard configuration errors and quick methods to resolve them.
Issue 1: nvm: command not found
This error occurs when the shell environment path lines are not properly loaded or when you run installation instructions in a non-interactive shell.
The Solution:
Add the environment configuration block manually to your local ~/.bashrc file:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # Loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # Loads nvm bash_completion
Save your changes, reload your terminal configurations (source ~/.bashrc), and verify the installation.
Issue 2: EACCES: permission denied on Global Installs
This error occurs when NPM attempts to write to a root-owned folder /usr/lib/node_modules during global package installation.
The Solution:
Avoid running sudo npm install -g. Instead, use NVM, which runs securely within your home user space. Alternatively, manually remap NPM's global directory to a folder you own:
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
Add export PATH=~/.npm-global/bin:$PATH to your terminal profile config (~/.bashrc) and run source ~/.bashrc.
Issue 3: Port 3000 Already in Use
This occurs when a background Node.js thread continues running and holds onto a port, preventing a newly updated server process from booting.
The Solution:
Find the process ID (PID) currently listening on port 3000:
sudo lsof -i :3000
Terminate the blocking process using its PID:
sudo kill -9 <PID>
FAQ: Node.js on Ubuntu Common Questions
Which Node.js version should I install on Ubuntu for production?
Production applications should run exclusively on active LTS (Long-Term Support) versions. In 2026, Node.js 24 LTS and Node.js 22 LTS are the recommended choices. Node.js 20 went End-of-Life (EOL) in early 2026 and should be upgraded to ensure your application continues receiving critical security patches.
How do I completely uninstall Node.js from my Ubuntu server?
If you installed Node.js using APT or the NodeSource repository, purge the application files and clean up any remaining orphaned dependencies:
sudo apt-get purge nodejs npm -y
sudo apt-get autoremove -y
If you installed Node.js using NVM, run the following commands:
# Deactivate active NVM profiles
nvm deactivate
# Delete the NVM configurations directory
rm -rf ~/.nvm
Does installing Node.js also install NPM?
Yes, modern NodeSource and NVM installations bundle compatible, stable releases of NPM automatically. If you use the default Ubuntu APT package manager, you must install NPM separately using sudo apt install npm.
Deploying Your Application
Selecting the right installation method simplifies your deployment process. For development machines, NVM provides the flexibility to switch runtime versions on the fly. For production servers, NodeSource ensures reliable and consistent builds.
However, a proper setup is only half the battle. High-performance applications require optimized hosting environments to run efficiently.
Ready to take your Node.js application live to users? Don't let cheap, shared resources crash your system under load. Build your backend on a scalable, premium virtual platform. Explore InterData VPS Server Solutions today and enjoy enterprise-level hardware with instant automated provisioning.

Top comments (0)