RHEL BasedRocky Linux

How To Install Node.js on Rocky Linux 10

Install Node.js on Rocky Linux 10

Node.js has revolutionized server-side development by bringing JavaScript to the backend. Built on Chrome’s powerful V8 engine, this open-source runtime environment enables developers to create fast, scalable network applications using a single programming language across the entire stack. Rocky Linux 10, as an enterprise-grade distribution, provides the perfect foundation for hosting Node.js applications with its stability, security, and long-term support.

This comprehensive guide walks you through three proven methods to install Node.js on Rocky Linux 10. Whether you’re a system administrator setting up production servers or a developer building the next generation of web applications, you’ll find detailed instructions, practical examples, and troubleshooting tips to get Node.js running smoothly on your system. We’ll cover installation from the default AppStream repository, the NodeSource repository for latest releases, and Node Version Manager (NVM) for flexible version control.

Understanding Node.js and Its Benefits on Rocky Linux 10

Node.js is more than just a JavaScript runtime—it’s a complete ecosystem for building modern applications. At its core, Node.js uses an event-driven, non-blocking I/O model that makes it exceptionally efficient and lightweight. This architecture allows Node.js to handle thousands of concurrent connections without the overhead of traditional threading models.

The platform excels at building RESTful APIs, microservices architectures, real-time chat applications, streaming services, and IoT backends. Developers appreciate Node.js for its vast package ecosystem through npm (Node Package Manager), which hosts over a million packages covering virtually every imaginable use case. The ability to use JavaScript on both frontend and backend simplifies development workflows and reduces context switching.

Rocky Linux 10 enhances these capabilities with enterprise-level stability and security. As a downstream, community-driven continuation of CentOS, Rocky Linux maintains binary compatibility with Red Hat Enterprise Linux (RHEL), ensuring your Node.js applications run on a battle-tested platform. The distribution receives regular security updates and benefits from a robust community of contributors and users.

Prerequisites for Installation

Before installing Node.js on your Rocky Linux 10 system, ensure you meet the following requirements. Your server should have at least 2GB of RAM for optimal performance, though Node.js can run on systems with less memory for development purposes. Root or sudo privileges are essential for installing system packages and configuring repositories.

An active internet connection is required to download Node.js packages and dependencies from remote repositories. Basic familiarity with the Linux command line will help you follow along with the installation steps. You’ll need terminal access either through SSH for remote servers or direct console access for local machines.

The system should have essential utilities like curl or wget for downloading installation scripts. The DNF package manager, which comes pre-installed with Rocky Linux 10, handles software installation and dependency resolution. If you plan to deploy Node.js applications in production, understanding firewall configuration will be beneficial for exposing your applications to network traffic.

Method 1: Installing Node.js from AppStream Repository

Rocky Linux 10 includes Node.js in its default AppStream repository, making it the simplest installation method. The AppStream repository uses a modular approach, allowing multiple versions of software to coexist. While this method may not provide the absolute latest Node.js release, it offers excellent stability and integration with the Rocky Linux ecosystem.

Update Your System Packages

Begin by updating your system to ensure all packages are current. Open your terminal and execute:

sudo dnf update -y

This command refreshes the package database and upgrades all installed packages to their latest versions. The -y flag automatically confirms the update without prompting. System updates are crucial for security patches and compatibility improvements. The process may take several minutes depending on your internet speed and the number of packages requiring updates.

Check Available Node.js Modules

Rocky Linux uses module streams to provide different versions of software. List available Node.js module streams:

dnf module list nodejs

This command displays all Node.js versions available through the AppStream repository. You’ll see information about available streams, profiles, and the default version. Module streams allow you to choose between different release versions while maintaining system stability.

Install Node.js from AppStream

Install Node.js using the module installation command:

sudo dnf module install nodejs:20 -y

This command installs Node.js version 20 along with npm (Node Package Manager). The installation automatically resolves dependencies and configures the necessary environment variables. The AppStream version may lag behind the latest upstream releases, but it receives security updates and bug fixes through the Rocky Linux update cycle.

Verify the Installation

Confirm Node.js installed correctly by checking its version:

node -v

You should see output like v20.x.x indicating the installed version. Verify npm installation with:

npm -v

This displays the npm version number, typically in the format 10.x.x. Both commands should execute without errors if the installation succeeded.

Method 2: Installing Node.js from NodeSource Repository

The NodeSource repository provides the latest Node.js releases directly from the official maintainers. This method is recommended for most users who need current features, recent performance improvements, and up-to-date security patches. NodeSource supports multiple Node.js versions including the current release and Long-Term Support (LTS) versions.

Why Choose NodeSource Repository

NodeSource serves as the official third-party repository for Node.js binaries on RPM-based distributions. The repository receives updates shortly after upstream releases, ensuring you always have access to the latest features. Unlike the AppStream repository, NodeSource provides Node.js 18.x, 20.x, and 22.x versions, allowing you to choose the release that best fits your requirements.

LTS versions receive active support for 30 months with bug fixes and security updates, making them ideal for production environments. Current releases include the latest features but have a shorter support lifecycle. NodeSource packages integrate seamlessly with DNF package management, allowing standard update procedures.

Install Required Dependencies

Ensure curl is installed on your system:

sudo dnf install curl -y

The curl utility downloads files from URLs and is essential for fetching the NodeSource setup script. Most Rocky Linux installations include curl by default, but this command ensures it’s available.

Add the NodeSource Repository

Download and execute the NodeSource setup script for Node.js 22.x:

curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -

This script performs several actions: it adds the NodeSource repository configuration to your system, imports the GPG signing keys for package verification, and updates the package database. The -fsSL flags make curl fail silently on errors, follow redirects, and suppress progress output while still showing errors.

For different Node.js versions, modify the URL accordingly. For Node.js 20.x LTS, use:

curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -

Always review scripts before executing them with bash, especially when running with sudo privileges. You can inspect the script first by downloading it or visiting the URL in a browser.

Install Node.js and npm

With the repository configured, install Node.js:

sudo dnf install nodejs -y

The installation includes the Node.js runtime, npm package manager, and necessary dependencies. The process downloads approximately 30-50 MB of packages and typically completes within a few minutes. DNF automatically handles dependency resolution and ensures all required libraries are present.

Verify Your Installation

Check the installed Node.js version:

node -v

You should see output like v22.11.0 or similar, depending on the current release. Verify npm:

npm -v

The npm version should be in the 10.x range for Node.js 22. These commands confirm that both the runtime and package manager are correctly installed and accessible from your PATH.

Install Development Tools (Optional)

Many npm packages include native addons that require compilation during installation. Install the development tools group:

sudo dnf groupinstall 'Development Tools' -y

This command installs gcc, g++, make, and other essential build tools. While not strictly necessary for running Node.js applications, these tools become crucial when working with packages like bcrypt, canvas, or node-sass that include C++ components. The Development Tools group also proves valuable for general system administration and software compilation tasks.

Method 3: Installing Node.js Using Node Version Manager (NVM)

Node Version Manager (NVM) provides the ultimate flexibility for managing multiple Node.js versions on a single system. Unlike system-wide installations, NVM operates at the user level, eliminating the need for sudo when installing or switching Node.js versions. This approach is particularly valuable for developers who test applications across different Node.js releases or maintain multiple projects with varying version requirements.

Understanding NVM’s Advantages

NVM shines in development environments where version flexibility matters. Each project can specify its required Node.js version, and NVM switches automatically when you enter the project directory. This isolation prevents version conflicts and ensures consistent behavior across different development machines.

System-wide installations require administrator privileges for updates and can only maintain one active version at a time. NVM, by contrast, allows unlimited installed versions with instant switching. The per-user installation model means different team members can use different Node.js versions without interfering with each other or system services.

NVM also simplifies testing new Node.js releases. Install a new version, test your applications, and rollback instantly if issues arise. The tool integrates with popular shells including bash, zsh, and fish.

Download and Install NVM

Execute the NVM installation script:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash

This script downloads NVM to ~/.nvm in your home directory and adds initialization code to your shell profile (~/.bashrc, ~/.zshrc, or ~/.profile). The installation modifies your shell configuration to load NVM automatically in new terminal sessions. The process completes in seconds and doesn’t require root privileges.

Activate NVM in Your Current Session

Reload your shell configuration:

source ~/.bashrc

For zsh users, source ~/.zshrc instead. Alternatively, close and reopen your terminal to apply the changes. Verify NVM installed correctly:

nvm --version

The command should display the NVM version number, confirming successful installation.

Install Node.js with NVM

Install the latest Node.js version:

nvm install node

The keyword “node” refers to the current release. NVM downloads, compiles (if necessary), and installs Node.js in seconds. For the latest LTS version, use:

nvm install --lts

LTS versions are recommended for production applications due to their extended support periods and stability. Install specific versions by providing the version number:

nvm install 20.11.0

NVM maintains separate installations for each version, allowing you to keep multiple releases simultaneously.

Manage Multiple Node.js Versions

List all installed versions:

nvm ls

This command shows your installed versions, the default version, and the currently active version. The output uses arrows to indicate the current and default versions.

Switch to a different installed version:

nvm use 20.11.0

The version becomes active immediately in your current shell session. Set a default version that loads automatically:

nvm alias default 20.11.0

For project-specific versions, create a .nvmrc file in your project root containing the version number:

20.11.0

Navigate to the project directory and run:

nvm use

NVM automatically reads the .nvmrc file and switches to the specified version. This approach ensures team members use consistent Node.js versions across development environments.

Managing npm Packages Effectively

The Node Package Manager (npm) comes bundled with Node.js and serves as the gateway to millions of open-source packages. Understanding npm basics is essential for Node.js development. Packages install either globally (system-wide or user-wide with NVM) or locally (per-project).

Global packages provide command-line tools accessible from anywhere. Install globally with the -g flag:

npm install -g pm2

Local packages install in your project’s node_modules directory and appear in package.json. Install locally by omitting the -g flag:

npm install express

Initialize a new Node.js project with:

npm init -y

This creates a package.json file tracking your project’s dependencies and metadata. The -y flag accepts all defaults, which you can modify later.

Update npm itself to the latest version:

npm install -g npm@latest

Regular npm updates provide bug fixes, performance improvements, and new features. Check for outdated packages:

npm outdated

Run security audits to identify vulnerabilities:

npm audit

Automatically fix vulnerabilities when possible:

npm audit fix

Popular global packages for development include:

  • pm2: Production process manager with load balancing
  • nodemon: Auto-restarts applications during development when files change
  • typescript: JavaScript superset with static typing
  • eslint: Code linting and style enforcement
  • yarn: Alternative package manager with deterministic installs

Creating Your First Node.js Application

Practical experience solidifies understanding. Let’s create a simple HTTP server to verify your Node.js installation and demonstrate basic functionality.

Initialize Your Project

Create a project directory:

mkdir ~/my-node-app
cd ~/my-node-app

Initialize the npm project:

npm init -y

This generates a package.json file with default values. The file tracks dependencies, scripts, and project metadata.

Build a Simple Web Server

Create the application file:

nano app.js

Add the following code:

const http = require('http');

const hostname = '0.0.0.0';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello from Node.js on Rocky Linux 10!\n');
});

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

Save and exit (Ctrl+X, then Y, then Enter in nano). This code creates a basic HTTP server using Node.js’s built-in http module. The server listens on port 3000 and responds to all requests with a simple text message.

Run Your Application

Start the server:

node app.js

You should see: “Server running at http://0.0.0.0:3000/”. Test the server from another terminal:

curl http://localhost:3000

The command returns: “Hello from Node.js on Rocky Linux 10!” Press Ctrl+C to stop the server.

Using PM2 for Production

PM2 is a production-grade process manager that keeps applications running, restarts them on crashes, and provides monitoring capabilities. Install PM2 globally:

npm install -g pm2

Start your application with PM2:

pm2 start app.js

PM2 runs the application in the background and monitors its health. List running processes:

pm2 list

View real-time logs:

pm2 logs

Stop the application:

pm2 stop app.js

Restart the application:

pm2 restart app.js

Configure PM2 to start on system boot:

pm2 startup
pm2 save

These commands generate and enable a systemd service that launches PM2 and your applications automatically after server restarts.

Configuring Firewall Rules for Node.js

Rocky Linux 10 uses firewalld for firewall management. By default, the firewall blocks incoming connections to non-standard ports like 3000. Configure firewall rules to allow external access to your Node.js applications.

Check firewalld status:

sudo systemctl status firewalld

The service should be active and running. Allow traffic on port 3000:

sudo firewall-cmd --permanent --add-port=3000/tcp

The --permanent flag ensures the rule persists across reboots. Reload firewall rules to apply changes:

sudo firewall-cmd --reload

Verify the port is open:

sudo firewall-cmd --list-ports

You should see 3000/tcp in the output. Test external access from another machine using curl or a web browser.

For production deployments, avoid exposing Node.js directly to the internet. Instead, use a reverse proxy like nginx or Apache on standard HTTP/HTTPS ports (80/443). The reverse proxy handles SSL termination, load balancing, and static file serving while forwarding dynamic requests to Node.js. This architecture provides better security, performance, and flexibility.

Configure nginx as a reverse proxy by allowing HTTP and HTTPS:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Handling Multiple Node.js Versions

Version management becomes crucial in diverse development environments. Different projects may require specific Node.js versions due to compatibility requirements or feature dependencies. NVM excels at this scenario, but understanding version management principles benefits all users.

LTS versions receive maintenance for 30 months from their initial release, making them suitable for production applications where stability trumps bleeding-edge features. Current versions include the latest JavaScript features and performance optimizations but transition out of active development more quickly.

Projects should specify their Node.js version requirements in documentation and configuration files. The .nvmrc file provides an elegant solution for NVM users, enabling automatic version switching when entering project directories. Add this line to your shell configuration for automatic switching:

# Place in ~/.bashrc or ~/.zshrc
cdnvm() {
    cd "$@" || return $?
    nvm_path=$(nvm_find_up .nvmrc | tr -d '\n')
    if [[ ! $nvm_path = *[^[:space:]]* ]]; then
        declare default_version;
        default_version=$(nvm version default);
        if [[ $default_version == "N/A" ]]; then
            nvm alias default node;
            default_version=$(nvm version default);
        fi
        if [[ $(nvm current) != "$default_version" ]]; then
            nvm use default;
        fi
    elif [[ -s $nvm_path/.nvmrc && -r $nvm_path/.nvmrc ]]; then
        declare nvm_version
        nvm_version=$(<"$nvm_path"/.nvmrc)
        declare locally_resolved_nvm_version
        locally_resolved_nvm_version=$(nvm ls --no-colors "$nvm_version" | tail -1 | tr -d '\->*' | tr -d '[:space:]')
        if [[ "$locally_resolved_nvm_version" == "N/A" ]]; then
            nvm install "$nvm_version";
        elif [[ $(nvm current) != "$locally_resolved_nvm_version" ]]; then
            nvm use "$nvm_version";
        fi
    fi
}
alias cd='cdnvm'

Remove old Node.js versions to free disk space:

nvm uninstall 18.0.0

Troubleshooting Common Installation Issues

Even straightforward installations sometimes encounter problems. Here are solutions to frequent issues.

Permission Denied Errors: These typically occur when installing global npm packages without proper permissions. With system-wide Node.js installations, use sudo for global packages. With NVM, sudo is unnecessary and actually causes problems by installing packages in root’s directory instead of your user directory.

Command Not Found: If node or npm commands aren’t recognized, check your PATH configuration. For AppStream and NodeSource installations, verify packages installed correctly with dnf list installed | grep nodejs. For NVM, ensure your shell profile loads NVM by checking .bashrc or .zshrc for NVM initialization code.

Module Not Found Errors: These indicate missing dependencies. Run npm install in your project directory to install all packages listed in package.json. For missing global modules, install them with npm install -g package-name.

Port Already in Use: When starting a Node.js application, “port already in use” errors mean another process is listening on that port. Find the process:

sudo lsof -i :3000

Or:

sudo netstat -tulpn | grep :3000

Kill the process using the port:

sudo kill -9 <PID>

EACCES Errors: These npm permission errors occur during global package installation on system-wide Node.js installations. Solutions include using NVM, changing npm’s default directory, or fixing npm permissions. The safest approach is switching to NVM for development.

Repository Errors: If DNF can’t find packages, clear the cache and rebuild metadata:

sudo dnf clean all
sudo dnf makecache

Version Conflicts: Installing Node.js through multiple methods causes conflicts. Choose one installation method and remove others. Uninstall AppStream packages before using NodeSource, or vice versa.

Updating Node.js to Newer Versions

Keeping Node.js current ensures you benefit from performance improvements, new features, and critical security patches. Update procedures vary by installation method.

AppStream Repository: Update with standard DNF commands:

sudo dnf update nodejs

This installs the latest version available in your enabled module stream. To switch module streams, reset the current stream and enable a different one:

sudo dnf module reset nodejs
sudo dnf module enable nodejs:22
sudo dnf module install nodejs:22

NodeSource Repository: Download and run the setup script for the desired version, then update:

curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
sudo dnf update nodejs

The setup script updates repository configuration, allowing DNF to install the new version.

NVM: Install the new version and set it as default:

nvm install 22.0.0
nvm alias default 22.0.0

NVM maintains old versions unless explicitly removed. Test new versions before updating production applications. Review release notes for breaking changes, especially between major versions. Node.js follows semantic versioning—major version updates may break existing code.

Uninstalling Node.js Cleanly

Complete removal requires cleaning up packages, repositories, and configuration files.

Remove AppStream Installation:

sudo dnf module remove nodejs
sudo dnf module reset nodejs

Remove NodeSource Installation:

sudo dnf remove nodejs
sudo rm -f /etc/yum.repos.d/nodesource*.repo
sudo dnf clean all

Remove NVM Installation:

rm -rf ~/.nvm

Edit .bashrc or .zshrc and remove NVM initialization lines. Remove global npm packages before uninstalling Node.js:

npm ls -g --depth=0
npm uninstall -g package-name

Best Practices for Production Deployments

Production environments require additional considerations beyond basic installation. Always use LTS versions for production applications due to their extended support and stability. Current versions suit experimentation and non-critical applications but lack the long-term guarantees needed for production.

Run Node.js applications as dedicated non-root users. Create a service account:

sudo useradd -r -s /bin/false nodeapp

Configure PM2 or systemd to manage application processes. Process managers automatically restart crashed applications, aggregate logs, and facilitate deployments. Never rely on manual node app.js commands in production.

Deploy Node.js behind a reverse proxy like nginx or Apache. The reverse proxy handles SSL/TLS termination, static file serving, request routing, and load balancing. This architecture shields Node.js from direct internet exposure and leverages each component’s strengths.

Implement comprehensive logging using Winston, Bunyan, or Pino. Aggregate logs to centralized systems for monitoring and troubleshooting. Enable health check endpoints that monitoring systems can poll to verify application availability.

Use environment variables for configuration rather than hardcoding values. Tools like dotenv facilitate local development while production environments inject variables through systemd or container orchestration platforms.

Enable security headers in your applications. Libraries like helmet.js automatically configure appropriate headers to protect against common vulnerabilities. Keep dependencies updated and run regular security audits with npm audit.

Implement proper error handling and graceful shutdown procedures. Applications should catch unhandled exceptions, log errors, and shut down cleanly when receiving termination signals. This prevents data corruption and allows process managers to restart services reliably.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button