RHEL BasedRocky Linux

How To Install NestJS on Rocky Linux 9

Install NestJS on Rocky Linux 9

NestJS has quickly become a popular choice for building scalable server-side applications with Node.js. Its modular architecture, TypeScript support, and robust toolset make it ideal for projects ranging from small APIs to complex enterprise systems. Meanwhile, Rocky Linux 9 provides a stable enterprise-ready operating system that benefits from the legacy of CentOS, making it a suitable platform for your Node.js and NestJS needs. By following best practices, you can set up a smooth development workflow and a secure production environment on Rocky Linux 9.

In this article, we will walk through the entire process of installing and configuring NestJS on your Rocky Linux 9 system. We will cover essential steps such as preparing the operating system, installing the latest Node.js version, initializing a NestJS project, configuring environment variables, and finally deploying your application. You will also learn how to troubleshoot common issues, keep your environment secure, and optimize performance for real-world deployment scenarios.

Our goal is to guide you through every detail while ensuring you get the most out of this powerful stack. By the end of this tutorial, you will have a fully functioning NestJS application running on Rocky Linux 9, ready to serve web traffic or power APIs. If you are comfortable working in a terminal and have basic knowledge of Linux and Node.js, you will find this guide extensive yet easy to follow. Let’s get started with the initial system preparation for Rocky Linux 9.

System Preparation

Before installing any software, particularly in a production or semi-production environment, it is essential to have your system up to date. Ensuring that Rocky Linux 9 is current with the latest packages, security patches, and firmware is the first step in maintaining stability. Below is a checklist for preparing your Rocky Linux system.

1. Update Your Rocky Linux 9 System

The first task is to refresh the package repositories and upgrade existing packages. Use the following commands:

sudo dnf update -y
sudo dnf upgrade -y

Once the update finishes, reboot your system to ensure that all changes are applied, especially if the kernel has been upgraded:

sudo reboot

2. Verify System Specifications

After reboot, verify that your system meets the resource requirements for running Node.js and NestJS. While these frameworks can perform well on moderate hardware, having sufficient CPU cores and memory depends on your workload. A single-core CPU with 1 GB of RAM is fine for minimal testing, but for production deployments, consider at least 2-4 cores and 2-4 GB of RAM.

3. Basic Security Settings

Rocky Linux 9 includes firewalld by default. Confirm that it is active:

sudo systemctl status firewalld

If it is not active, enable it:

sudo systemctl enable firewalld --now

Open necessary ports for development and testing later, such as port 3000 (the default NestJS port):

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

By following these simple measures, you will reduce the risk of unauthorized access and create a more controlled environment. Next, we’ll move on to the dependencies required for Node.js and NestJS installation.

Node.js Installation

Node.js is the backbone of any NestJS application, providing the JavaScript runtime environment required to run server-side code. A stable and up-to-date version of Node.js ensures optimal performance and broad compatibility with third-party libraries or frameworks. Below we detail both the Node Version Manager (NVM) approach and an alternative method using the Rocky Linux repositories.

1. Install Required Packages

Before installing Node.js, make sure you have some essential developer tools and libraries:

sudo dnf groupinstall "Development Tools" -y
sudo dnf install openssl-devel

Installing these packages ensures that you have everything needed to compile modules from source if necessary.

2. Install Node Version Manager (NVM)

NVM simplifies Node.js version management by allowing multiple Node.js versions to coexist. This is highly useful if you plan to test different versions of Node.js for various NestJS projects.

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

The version number may change, so replace it with the latest release if needed. After installation, load NVM into your current shell:

source ~/.bashrc

Verify the installation by checking the NVM version:

nvm --version

3. Install Node.js Using NVM

Once NVM is set up, you can choose to install either the latest LTS version or a specific release of Node.js:

nvm install --lts

To use your newly installed Node.js version by default each time you open a shell session, run:

nvm alias default <version>

For instance, if the LTS version you installed is 18.16.0, you would type:

nvm alias default 18.16.0

Confirm your Node.js and npm versions:

node -v
npm -v

Having completed these steps, you now have a stable and flexible Node.js environment that will serve as the foundation for your NestJS installation.

Installing NestJS

NestJS builds on top of Express (or optionally Fastify) to provide a structured framework for rapidly developing Node.js applications in TypeScript. By installing the NestJS Command Line Interface (CLI), you can easily create boilerplate code, generate modules, and streamline your development workflow. Below are step-by-step instructions on installing and initializing a NestJS project on Rocky Linux 9.

1. Global Installation of the NestJS CLI

Install the NestJS CLI globally using npm:

npm install -g @nestjs/cli

The CLI simplifies project creation and includes scripts for building, running, and testing your application. After installation, verify it:

nestjs --version

2. Creating a New NestJS Project

To start a brand new NestJS project, navigate to the directory where you want to store your application code:

cd ~

Then initialize a new NestJS application:

nestjs new my-nestjs-app

Replace my-nestjs-app with the name of your own project. The CLI will prompt you to choose a package manager. Select npm or yarn, depending on your preference. This command creates a new folder with a default NestJS structure, which includes fundamental directories like src for your code and test for your tests.

3. Project Structure Overview

By default, the newly created application adheres to NestJS’s opinionated architecture. Understanding this structure helps you navigate and organize your files:

  • main.ts: Bootstraps the NestJS application.
  • app.module.ts: Declares the main application module.
  • app.controller.ts: Example controller showing how to handle incoming requests.
  • app.service.ts: Example provider demonstrating encapsulated logic.
  • app.controller.spec.ts: Basic test file for the app controller.

This structure enforces separation of concerns, which fosters scalable and maintainable applications. You can add new modules, services, and controllers as your project grows.

4. Installing Additional Dependencies

Depending on your project requirements, install additional libraries or modules. For example, if you plan to connect to a database like PostgreSQL, you might install TypeORM:

npm install --save @nestjs/typeorm typeorm pg

Likewise, if you need environment variable management, consider adding cross-env or dotenv:

npm install cross-env

With the CLI installed and your project set up, you now have the foundation needed to explore and customize NestJS for your application’s needs. Next, let’s configure our development environment and test our NestJS installation.

Configuration and Testing

Proper configuration and robust testing are crucial for any production-grade application. NestJS offers environment management, TypeScript features, and built-in testing utilities to ensure your application behaves as expected. In this section, we will set up environment variables, configure the application in both development and production modes, and confirm that everything runs smoothly on Rocky Linux 9.

1. Setting Up Environment Variables

Use environment variables to store sensitive or configurable data. NestJS optionally integrates well with dotenv to manage these variables. Begin by installing dotenv if needed:

npm install dotenv --save

Create a .env file at the root of your project:

touch .env

In the main.ts or in a custom configuration service, load these variables:

import { ConfigService } from '@nestjs/config';

...

const configService = new ConfigService();
const port = configService.get('PORT') || 3000;

This approach allows you to keep the same codebase while switching environment files, which is very handy for production deployments.

2. Running the Development Server

Inside your project’s directory, start the development server:

npm run start:dev

Open your web browser and navigate to http://<server-IP>:3000 (or http://localhost:3000 if you are testing locally). If you see NestJS’s default “Hello World!” response (or whichever controller response you configured), your setup is correct.

3. Production Configuration

For a production environment, you might want to build and run your application in a more optimized manner:

npm run build
npm run start:prod

This sequence compiles your TypeScript code into JavaScript and then launches NestJS with performance optimizations. Make sure your firewall settings allow incoming traffic on port 3000 (or any port you have configured for your application).

4. Testing the Application

NestJS includes a ready-to-use testing framework out of the box. You can run tests with:

npm run test

Or run tests in watch mode:

npm run test:watch

Using tests ensures that your controllers, services, and other modules work exactly as intended. If any test fails, fix the underlying code issues before moving forward. At this point, it’s wise to keep your repository organized with meaningful commits and push changes frequently to remote version control, such as GitHub or GitLab.

Production Deployment

Once you have confirmed that your NestJS application runs smoothly in a development environment, it’s time to consider deploying it for production on Rocky Linux 9. A secure and optimized deployment ensures that your application remains robust under load and protected from potential threats. Below are some best practices and step-by-step instructions for hardening your system and optimizing performance.

1. Security Considerations

  • Set Up SSL/TLS: Installing an SSL certificate ensures encrypted communication with your server. Tools like Let’s Encrypt or a commercial SSL certificate provider can help you quickly enable HTTPS.
  • Process Management: Use a process manager like PM2 or forever to keep your application running, automatically restarting it if it crashes. For example:
    npm install -g pm2
    pm2 start dist/main.js --name "nestjs-app"
    pm2 startup
    pm2 save
    
  • Firewall Configuration: Restrict incoming traffic to essentials (e.g., ports 22 for SSH, 80 for HTTP if needed, and 443 for HTTPS). Keep NestJS behind a reverse proxy on production if it simplifies your environment.

2. Performance Optimization

Optimizing performance often involves caching, load balancing, and proper resource allocation.

  • Configure Caching: Leverage in-memory caches like Redis or Memcached to speed up repeated data retrieval.
  • Horizontal Scaling: For high-traffic applications, consider running multiple NestJS instances behind a load balancer such as Nginx or HAProxy. This approach distributes the workload and improves throughput.
  • Monitoring: Implement logging and monitoring tools like Winston or Grafana to track performance metrics.

3. Ongoing Maintenance

Periodic updates ensure your Rocky Linux server and NestJS packages remain secure. Regularly check for updates and patches:

sudo dnf update -y
npm outdated

Additionally, remove unnecessary packages to minimize the attack surface. Keep your code repository well-organized, and document any changes you make to your system or application.

With these security and performance practices in place, you can confidently serve your NestJS projects to production users on Rocky Linux 9. When your application is running reliably, you’ll still want to be prepared for any potential issues, which we’ll cover in the next section on troubleshooting.

Troubleshooting Guide

Even carefully planned installations can encounter unexpected hurdles, and NestJS deployments are no exception. Below are some common issues you may face when working with NestJS on Rocky Linux 9, along with quick solutions.

  • Port Conflicts: If NestJS fails to start because port 3000 is already in use, find the offending process:
    sudo lsof -i :3000
    sudo kill -9 <PID>
    

    Then restart NestJS.

  • Missing Dependencies: If you encounter Module Not Found errors, confirm you installed the package globally vs locally, ensure node_modules is present, and re-run:
    npm install
    
  • Version Compatibility: Sometimes certain NestJS or Node.js versions conflict with each other. Switch to a stable Node.js version with NVM and update NestJS:
    nvm use <another-version>
    npm i -g @nestjs/cli
    
  • Firewall Blocks: If the service seems to run but you cannot access it, verify that the firewall allows incoming traffic on the correct port and that SELinux rules are not preventing the connection.

By systematically checking these areas, you can typically isolate and fix most problems quickly. If you still encounter bugs, turning on debugging in NestJS or reviewing system logs will help you identify underlying causes.

Congratulations! You have successfully installed NestJS. Thanks for using this tutorial install the latest version of NestJS framework on Rocky Linux 9. For additional help or useful information, we recommend you check the official NestJS website.

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