pixel

How to install MERN Stack on Rocky Linux 9

Share on Social Media

Don’t get left behind! Learn how to install MERN Stack on Rocky Linux 9 with this step-by-step guide. Build full-stack apps faster, safer, and smarter—start coding like a pro today! #centlinux #linux #mongodb



Introduction – Install MERN Stack on Rocky Linux 9

Looking to build fast, modern web applications on a reliable Linux server? In this step-by-step guide, you’ll learn how to install MERN stack on Rocky Linux 9, a powerful combination that gives you everything you need to develop full-stack JavaScript applications.

The MERN stack—which stands for MongoDB, Express.js, React, and Node.js—is one of the most popular web development stacks today. It’s favored by developers for its speed, flexibility, and use of a single programming language (JavaScript) across both front-end and back-end development. With Node.js and React powering dynamic, high-performance web apps, MERN is a top choice for startups, enterprises, and solo developers alike.

So why choose Rocky Linux 9? As a stable, enterprise-grade Linux distribution that’s 100% bug-for-bug compatible with RHEL, Rocky Linux offers long-term support and reliability—making it an ideal server environment for hosting production-ready MERN applications.

Whether you’re a developer, system admin, or DevOps enthusiast, this guide will walk you through each step of setting up the MERN stack on Rocky Linux 9. Let’s get started!

How to install MERN Stack on Rocky Linux 9
How to install MERN Stack on Rocky Linux 9

System Requirements & Pre-Installation Checklist

Before diving into the MERN stack installation, it’s important to make sure your system is properly prepared. This ensures a smooth installation process and helps avoid common issues.

Minimum System Requirements

To run the MERN stack on Rocky Linux 9, your server should meet the following minimum specifications:

  • CPU: 1+ GHz processor (2+ cores recommended)
  • RAM: 2 GB minimum (4 GB or more recommended)
  • Storage: At least 20 GB of free disk space
  • OS: Rocky Linux 9 (64-bit)
  • Network: Stable internet connection

💡 For cloud environments, a basic Linux VPS like a 1 vCPU/2GB RAM instance (from AWS, Linode, DigitalOcean, etc.) works well for testing or small apps.


Pre-Installation Checklist

Let’s go through some essential system preparation steps before installing any MERN stack components.


1. Update your system packages

Keep the system up to date with the latest security patches and package versions.

sudo dnf update -y

This command ensures all installed packages are current. Keeping your system updated is critical for both security and compatibility.


2. Install essential development tools

Install basic tools and libraries needed for building Node.js packages and compiling native modules.

sudo dnf groupinstall "Development Tools" -y

This installs compilers and utilities required for building from source, often needed by npm packages during installation.


Instead of using the root account, create a new user with sudo privileges.

sudo useradd -m -s /bin/bash devuser
sudo passwd devuser
sudo usermod -aG wheel devuser
  • useradd creates a new user named devuser.
  • passwd sets the user’s password.
  • usermod adds the user to the wheel group, enabling sudo access.
YouTube player

4. Enable the Extra Packages for Enterprise Linux (EPEL) repository

EPEL provides additional packages that are not available in the default Rocky Linux repo.

sudo dnf install epel-release -y

This adds access to community-maintained software often needed for web and dev environments.


5. Verify your OS version

Make sure you’re running Rocky Linux 9.

cat /etc/os-release

You should see output similar to:

NAME="Rocky Linux"
VERSION="9.X (Blue Onyx)"

If you’re still on CentOS or another system, consider switching—CentOS has shifted focus, and Rocky Linux is its most trusted replacement.

Once you’ve completed these steps, your system is fully prepared for the MERN stack installation. In the next section, we’ll begin by installing Node.js.


Recommended Training: Angular & NodeJS – The MEAN Stack Guide [2025 Edition] from Maximilian Schwarzmüller

833442 b26e 5
show?id=oLRJ54lcVEg&bids=1597309

Installing Node.js and npm

Node.js is the runtime that powers both your backend (Express.js) and build tools for React. The npm (Node Package Manager) tool is used to install JavaScript packages. Let’s walk through the recommended ways to install them on Rocky Linux 9.

Tip: Always use a Long-Term Support (LTS) version of Node.js for production. See Node.js LTS releases.


NodeSource provides maintained, up-to-date builds of Node.js for Enterprise Linux systems like Rocky Linux.

Step 1: Add the NodeSource repository

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

This command downloads and runs the NodeSource installer for Node.js 18.x LTS, which adds the proper YUM repository and prepares your system.

You can replace 18.x with another version if needed. Visit NodeSource for version options.


Step 2: Install Node.js and npm

sudo dnf install -y nodejs

This installs both Node.js and npm from the NodeSource repository.


Step 3: Verify the installation

node -v
npm -v

You should see version numbers confirming the installation, such as:

v18.18.2
9.8.1

Option 2: Install Node.js using nvm (Node Version Manager)

If you plan to manage multiple versions of Node.js (for different projects), nvm is a more flexible and developer-friendly choice.

Step 1: Download and install nvm

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

This script installs nvm and adds it to your shell profile.

Important: Close and reopen your terminal or run source ~/.bashrc to enable nvm.


Step 2: Install the latest LTS version of Node.js

nvm install --lts

This installs the latest LTS release and sets it as the default for your user.


Step 3: Verify installation

node -v
npm -v

nvm allows you to easily switch between versions with commands like nvm use 16 or nvm use 18.


Best Practice Summary

MethodWhen to UseBenefits
NodeSourceStable production environmentsSimple, system-wide install
nvmDevelopment, version switching, flexibilityPer-user control, version choice

Now that Node.js and npm are installed, you’re ready to move on to setting up MongoDB for the MERN stack.


Installing MongoDB on Rocky Linux 9

MongoDB is a high-performance NoSQL database used to store JSON-like documents. In the MERN stack, it serves as the back-end database that integrates seamlessly with Node.js applications.

We’ll install MongoDB 6.0, which is the latest stable release series. Let’s walk through the process step by step.

🔗 See the our detailed guide on How to install MongoDB on Linux Server 9 for more information.


Step 1: Create the MongoDB 6.0 YUM repository file

sudo tee /etc/yum.repos.d/mongodb-org-6.0.repo > /dev/null <<EOF
[mongodb-org-6.0]
name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/\$releasever/mongodb-org/6.0/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://pgp.mongodb.com/server-6.0.asc EOF

This command creates a new YUM repository configuration file pointing to the official MongoDB 6.0 repo for RHEL-compatible systems like Rocky Linux.

The gpgkey ensures secure package verification during installation.


Step 2: Install the MongoDB package

sudo dnf install -y mongodb-org

This installs the MongoDB server, client, and related tools from the repository we just added.


Step 3: Start and enable the MongoDB service

sudo systemctl enable --now mongod

This starts the mongod service immediately and ensures it starts automatically at boot.


Step 4: Check MongoDB service status

sudo systemctl status mongod

This displays the current status of MongoDB. Look for active (running) in the output.


Step 5: Allow MongoDB through the Linux firewall

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

This opens the default MongoDB port (27017) to allow remote connections if needed.

Only do this if MongoDB needs to be accessed from outside the server. Keep it closed for local development.


Step 6: Test MongoDB installation

mongosh

This opens the MongoDB shell, a CLI tool for interacting with your database. If it connects successfully, MongoDB is fully operational.

🔗 Learn more about mongosh from the MongoDB Shell Docs.


With MongoDB up and running, you’ve completed another major part of the MERN stack setup! Next, we’ll move on to installing Express.js and React.


Setting Up Express and Creating a Backend API

Now that you’ve installed MongoDB, it’s time to set up Express.js to create your backend API. Express is a minimal web framework for Node.js that will handle HTTP requests, while Mongoose will manage your MongoDB connections and schema. We’ll also use CORS for cross-origin requests and dotenv for environment variables.

Let’s break down the process step-by-step.

🔗 Explore Express here and learn more about Mongoose here.


Step 1: Initialize a Node.js Project

First, navigate to your project directory and initialize a Node.js project if you haven’t already.

mkdir my-mern-api
cd my-mern-api
npm init -y

This will create a package.json file with default settings. You can always modify it later.


Step 2: Install Required Packages

We need to install the following packages:

  • express: Web framework for building APIs
  • mongoose: MongoDB ODM for interacting with MongoDB
  • cors: Middleware for handling cross-origin requests
  • dotenv: Environment variable manager for securely storing sensitive data
npm install express mongoose cors dotenv

These packages will help set up the backend API and manage MongoDB connections securely.


Step 3: Create the server.js File

Now, create your server.js file, which will serve as the entry point for your Express API.

touch server.js

Open server.js in a code editor and add the following code:

// server.js

// Import necessary modules
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();

// Initialize the Express app
const app = express();

// Middleware setup
app.use(cors()); // Allow cross-origin requests
app.use(express.json()); // Parse incoming JSON requests

// MongoDB connection using Mongoose
mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log('MongoDB connected successfully');
    })
    .catch((err) => {
        console.error('MongoDB connection error:', err);
    });

// Sample route for testing the API
app.get('/', (req, res) => {
    res.send('Hello, MERN Stack!');
});

// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Explanation:

  • express.json(): This middleware parses incoming JSON requests.
  • mongoose.connect(): This establishes a connection to MongoDB using the connection string stored in the .env file.
  • cors(): This middleware enables cross-origin requests, which is essential when your front-end and back-end are hosted on different domains.

Step 4: Set Up the .env File

To store your environment variables securely (like your MongoDB URI), create a .env file in the root of your project:

touch .env

Add the following variables to your .env file:

MONGODB_URI=mongodb://localhost:27017/mydb
PORT=5000
  • MONGODB_URI: This is your MongoDB connection string. You’ll need to replace it with your actual MongoDB URI if you’re using a cloud database (like MongoDB Atlas).
  • PORT: This specifies the port number your API will listen on.

Security tip: Never commit .env files to version control! Add it to your .gitignore.


Step 5: Start the Server

You can now start your Express server with the following command:

node server.js

This will start your backend API on port 5000 (or the port specified in your .env file). If successful, you should see:

MongoDB connected successfully
Server is running on port 5000

Open your browser and navigate to http://localhost:5000. You should see the message “Hello, MERN Stack!” indicating that your server is up and running.


Step 6: Test the API with Postman or cURL

To confirm everything is working, test your API using a tool like Postman or cURL by making a GET request to http://localhost:5000.

Example with cURL:

curl http://localhost:5000

You should receive:

Hello, MERN Stack!

Step 7: Real-World Example: Using Mongoose to Create a Model

To create a simple API that interacts with MongoDB, let’s set up a basic Mongoose model. For example, let’s create a User model.

Create a new folder named models and inside it, create User.js:

mkdir models
touch models/User.js

Define the User schema in models/User.js:

const mongoose = require('mongoose');

// Create a user schema
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    age: Number
});

// Create the User model
const User = mongoose.model('User', userSchema);

module.exports = User;

Step 8: Integrating the Model in server.js

In server.js, you can now import the User model and create a route to interact with the database:

const User = require('./models/User');

// POST route to create a new user
app.post('/users', async (req, res) => {
    const { name, email, age } = req.body;

    try {
        const newUser = new User({ name, email, age });
        await newUser.save();
        res.status(201).json(newUser);
    } catch (err) {
        res.status(500).json({ error: 'Error creating user' });
    }
});

This route listens for a POST request to /users, creates a new user from the request body, and saves it to MongoDB.


Summary

You’ve now successfully:

  1. Set up an Express backend API.
  2. Connected it to MongoDB using Mongoose.
  3. Managed CORS and environment variables with dotenv.
  4. Created a simple API that allows adding users to the database.

Next, you can expand this API with more routes, authentication, and more complex logic.


Installing React and Creating the Frontend App

Now that we have the Express backend running, it’s time to set up the React frontend. React is a powerful JavaScript library for building user interfaces, and it will allow us to create interactive, dynamic web pages that communicate with our Express API.

We’ll use Create React App to quickly set up a React project, then modify the app to fetch data from our backend Express API.

🔗 You can explore React in more detail on the official React Docs and Create React App documentation.


Step 1: Install React using npx create-react-app

The easiest way to create a new React app is to use create-react-app. It sets up all the necessary files and configurations for you.

Run the following command in your project directory (outside the my-mern-api folder, for example):

npx create-react-app my-mern-frontend

This will create a new directory called my-mern-frontend with all the necessary files for a React app.

💡 npx runs the latest version of create-react-app without needing to install it globally.


Step 2: Run the React Development Server

Once the installation is complete, navigate to your React project folder and start the development server:

cd my-mern-frontend
npm start

This will start the React development server on http://localhost:3000 by default. You should see the default React welcome page in your browser.


Step 3: Modify App.js to Fetch Data from the Express API

Now, let’s modify the default App.js to fetch data from the Express API we set up earlier. We’ll use JavaScript’s fetch() API to make requests to the backend.

Open src/App.js and replace the existing code with the following:

import React, { useEffect, useState } from 'react';
import './App.css';

function App() {
  // State to store data fetched from the backend
  const [message, setMessage] = useState('');

  // Fetch data from the Express API when the component mounts
  useEffect(() => {
    fetch('http://localhost:5000')
      .then((response) => response.text()) // Parse the response as text
      .then((data) => setMessage(data)) // Set the fetched data to the state
      .catch((error) => console.error('Error fetching data:', error));
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <h1>Welcome to the MERN Stack App</h1>
        <p>{message}</p> {/* Display the message fetched from the API */}
      </header>
    </div>
  );
}

export default App;

Explanation:

  • useState: We use the useState hook to store the message that we’ll fetch from the backend.
  • useEffect: This hook is used to make the API call when the component mounts (i.e., when the page loads).
  • fetch(): We use fetch() to send a GET request to the Express backend. In this case, it’s requesting data from http://localhost:5000, which is the endpoint we set up in the Express server.
  • setMessage(data): Once the data is fetched, we update the message state, which causes the component to re-render and display the data.

Step 4: Handle CORS for Cross-Origin Requests

Since your backend (Express) and frontend (React) are running on different ports (5000 and 3000, respectively), you need to allow cross-origin requests from the frontend to the backend.

In your Express backend (inside server.js), we already installed and configured CORS, but let’s double-check that it’s correctly set up:

const cors = require('cors');

// Enable CORS for all origins
app.use(cors());

This allows requests from any domain, including your React app running on port 3000.

You can modify the CORS configuration to be more restrictive if needed, allowing only specific origins to access your backend.


Step 5: Test the Application

  1. Make sure both the Express server and React development server are running:
    • Express backend should be running on port 5000 (run node server.js if it’s not).
    • React frontend should be running on port 3000 (run npm start if it’s not).
  2. Open your browser and navigate to http://localhost:3000. You should see a page that says: Welcome to the MERN Stack App Hello, MERN Stack! The message “Hello, MERN Stack!” is being fetched from the backend API (http://localhost:5000), and displayed on the frontend.

Step 6: Handling Errors and Loading States

To improve the user experience, you can add some error handling and a loading state while the data is being fetched. Here’s an updated version of the App.js file that includes these improvements:

import React, { useEffect, useState } from 'react';
import './App.css';

function App() {
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('http://localhost:5000')
      .then((response) => response.text())
      .then((data) => {
        setMessage(data);
        setLoading(false); // Stop loading when data is fetched
      })
      .catch((error) => {
        setError('Failed to fetch data');
        setLoading(false);
      });
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <h1>Welcome to the MERN Stack App</h1>
        {loading ? (
          <p>Loading...</p>
        ) : error ? (
          <p style={{ color: 'red' }}>{error}</p>
        ) : (
          <p>{message}</p>
        )}
      </header>
    </div>
  );
}

export default App;
  • loading: Displays a loading message until the data is fetched.
  • error: Displays an error message if the fetch fails.

Summary

You’ve now:

  1. Set up React using create-react-app.
  2. Created a simple API call to your Express backend using fetch().
  3. Implemented CORS to allow communication between the frontend and backend.
  4. Tested the app to display data fetched from the Express API.

Next, you can continue building out your React app and integrate more API endpoints!


Testing the Full MERN Stack Application

Now that you’ve set up the Express backend and React frontend as part of your MERN stack, it’s time to ensure everything works together smoothly. This section will walk you through testing both parts of the application, confirming your API endpoints are working, and ensuring your React app displays data fetched from your backend.

🔗 Check out Postman for easy API testing and exploration.


Step 1: Running Both Frontend and Backend

Before you start testing, make sure both the Express backend and React frontend are running:

  1. Run the Express backend on port 5000:
    • Navigate to your backend directory (my-mern-api) and run:
    node server.js Your backend should now be accessible at http://localhost:5000.
  2. Run the React frontend on port 3000:
    • Navigate to your frontend directory (my-mern-frontend) and run:
    npm start Your frontend should now be accessible at http://localhost:3000.

Expected Behavior:

  • The backend (http://localhost:5000) should respond to API requests (e.g., GET requests).
  • The frontend (http://localhost:3000) should fetch data from the backend and display it on the page.

Step 2: Test Express API Endpoints

Let’s first ensure your Express backend is working properly by testing the API with Postman or directly in your browser.

  1. Test the Root Endpoint (GET /): Open Postman or your browser and navigate to http://localhost:5000. Expected Response: Hello, MERN Stack! If you see this message, it means the Express backend is up and running correctly.
  2. Test Additional Endpoints (if created):
    If you’ve added other API routes (e.g., for creating users), use Postman to send POST or GET requests to those endpoints. For example:
    • POST /users (to create a new user):
      • Set the method to POST in Postman.
      • URL: http://localhost:5000/users
      • Body: JSON format
      { "name": "John Doe", "email": "john@example.com", "age": 30 }
    Expected Response: { "name": "John Doe", "email": "john@example.com", "age": 30, "_id": "someMongoId", "__v": 0 } If the data is saved in the database, you should receive a confirmation response.

Step 3: Test the React Frontend

Now let’s confirm that React is correctly fetching data from the backend API.

  1. Open http://localhost:3000 in your browser.
  2. Expected Behavior:
    • If the connection between React and Express is successful, you should see: Welcome to the MERN Stack App Hello, MERN Stack!
    • The message “Hello, MERN Stack!” is fetched from the Express API and displayed on the page.
  3. Check the Browser Console:
    If the page doesn’t load the expected message, open the Developer Tools in your browser and check the Console tab for any errors (e.g., CORS issues, failed API calls, etc.).
    • If you see a CORS error in the console, it means your backend isn’t allowing cross-origin requests. Check the CORS configuration in your Express app to ensure it’s set up correctly: app.use(cors());
    • If you see a Network error or 404 error for the API call, ensure the backend is running on the correct port (5000), and that the API endpoint you’re trying to access exists.

Troubleshooting Tips

If something isn’t working as expected, here are some troubleshooting tips:

  1. Backend Not Running:
    • Ensure you’ve started the backend server using node server.js.
    • Check for any errors in the terminal where you started the backend.
  2. CORS Issues:
    • If your browser is blocking the request, you might see a CORS error in the developer console. Ensure CORS middleware is enabled in your Express backend:
    app.use(cors());
  3. React Not Displaying Data:
    • Check if the fetch request in React is correctly pointing to the backend:
    fetch('http://localhost:5000')
  4. API Not Returning Expected Data:
    • Test the API with Postman to ensure it’s returning the correct data.
    • Double-check your Express routes to ensure they’re correctly handling requests.
  5. React Fetching Incorrect URL:
    • If you’re using environment variables for the backend URL, ensure that the correct URL is set in the .env file.

Summary

By now, you should have:

  1. Successfully run both the Express backend and React frontend together.
  2. Tested API endpoints using Postman or a browser to verify that the backend is working correctly.
  3. Confirmed that React can fetch data from the backend API and display it.

Now you can continue building your MERN stack application, adding more features like authentication, user management, and more.


Conclusion and Next Steps

Final Thoughts

Congratulations! 🎉 You’ve successfully installed and configured the MERN stack on Rocky Linux 9, setting up a fully functional development environment with:

  • MongoDB for your database,
  • Express.js and Node.js for your backend API,
  • React for your frontend interface.

You also learned how to test your full-stack application and confirmed that your React app can communicate with your Express API. This solid foundation puts you on the path to building modern, scalable web applications.

Looking for a Linux server expert? I provide top-tier administration, performance tuning, and security solutions for your Linux systems. Explore my Fiverr profile for details!

Read Also: How to install MEAN Stack on CentOS 7


What’s Next?

Here are some practical and powerful next steps to take your MERN project to the next level:

  • 🔐 Implement JWT Authentication
    Secure your API routes by adding JWT (JSON Web Token) based authentication and authorization.
  • 🐳 Dockerize Your Application
    Package your app with Docker to simplify deployment and make it portable across environments.
  • ☁️ Deploy to the Cloud
    Take your app live by deploying it to a cloud platform like Hostinger, AWS, or Heroku. You can use services like Docker Compose or CI/CD pipelines to streamline the process.

Looking for something?

Leave a Reply