How To Install MEAN Stack on Ubuntu 24.04 LTS
A strong web application environment requires a reliable and efficient technology stack. When it comes to crafting modern, feature-rich, and scalable web apps using JavaScript end-to-end, few options rival the MEAN stack. Composed of MongoDB, Express.js, Angular, and Node.js, the MEAN stack streamlines development processes by employing a single language (JavaScript) for both client-side and server-side work. By integrating NoSQL data handling with server logic, front-end frameworks, and robust libraries, this approach simplifies deployment while boosting performance.
This guide provides a comprehensive tutorial on how to install the MEAN stack on Ubuntu 24.04. The instructions include everything from basic system updates and prerequisites to configuring each component. Throughout the article, you will find step-by-step details, troubleshooting guidance, and essential security considerations. By the end, you will have a fully operational MEAN stack, ready to power your next dynamic project.
Prerequisites
Before proceeding with the installation on your Ubuntu 24.04 system, ensure that you meet the following requirements:
- Ubuntu 24.04 Installation: Have an updated and running Ubuntu 24.04 environment.
- Administrative Privileges: Access to a user account with
sudo
privileges. - Basic Linux Command Line Skills: Knowledge of essential terminal operations such as navigating directories, editing text files, and handling processes.
- Reliable Internet Connection: Required to download and install system packages and repositories.
Having these prerequisites met helps ensure a smooth installation. If you lack any of these components or if your system is out of date, take the time to update and configure them before setting up the MEAN stack. Once everything is in place, you can move forward with higher confidence, knowing your environment is prepared for the process ahead.
System Preparation
System preparation entails ensuring that Ubuntu’s packages, dependencies, and system configurations are up to date. This step can prevent common errors such as version conflicts and missing libraries. Failing to do so might lead to unpredictable behavior later in the installation process. Below are the steps to get your system ready:
Update and Upgrade
1. Open your terminal and run the following command to update your package list:
sudo apt update
2. Next, upgrade existing packages to their latest compatible versions:
sudo apt upgrade
3. Optionally, remove unwanted dependencies and packages that aren’t in use:
sudo apt autoremove
By keeping your system fresh and clean, you set a stable foundation for installing Node.js, MongoDB, Express.js, and Angular without running into conflicts. If any system updates require a reboot, proceed to reboot and then return to your terminal. It is best to proceed with a fully up-to-date and stable environment.
Installing Node.js
Node.js is a JavaScript runtime that allows you to run JavaScript code server-side. A core element of the MEAN stack, Node.js interacts with servers and frameworks, including Express.js, making it critical for both local development and production environments. The Node Package Manager (npm
) that comes with Node.js simplifies the process of installing additional packages and libraries.
Add the NodeSource Repository
Although Ubuntu’s repositories might already include Node.js, these versions can sometimes lag behind the latest stable releases. To ensure you have the most recent version, add NodeSource’s repository:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
This command automatically configures the appropriate repository on your system, allowing you to install an up-to-date version of Node.js.
Install Node.js and npm
After adding the repository, proceed with the installation:
sudo apt install nodejs
Once that’s complete, verify your installed versions:
node -v
npm -v
Having Node.js and npm installed and verified ensures that you can manage packages and run JavaScript code server-side without issues. If you see a version number for both, you’re all set to move on.
Configure npm (Optional)
If you want to change the default setting of npm’s global install location or set up proxy settings, you can do so by editing the npm configuration file. For instance, to move the default global install directory to your home folder:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
This ensures that you have more control over your environment. You might not need this if the default location and settings work for your use case. However, it can be useful for avoiding permission issues.
Installing MongoDB
MongoDB is a NoSQL database renowned for scalability, flexibility, and excellent performance. In the MEAN stack, it provides schema-less data management, allowing you to store JSON-like documents. Setting up MongoDB on Ubuntu 24.04 typically involves installing the community edition from an official MongoDB repository to maintain the latest stable version.
Add the MongoDB Repository
1. Import MongoDB’s GPG key:
curl -fsSL https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-6.0.gpg
2. Create a list file for MongoDB in your sources.list.d
directory:
echo "deb [signed-by=/usr/share/keyrings/mongodb-server-6.0.gpg] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
3. Update your package list to recognize the newly added repository:
sudo apt update
Install MongoDB Community Edition
With the repository set up, you can now install the MongoDB packages:
sudo apt install mongodb-org
This command installs the mongod
daemon and other MongoDB tools needed for managing the database.
Enable and Start MongoDB
To ensure MongoDB starts at system boot, enable the service:
sudo systemctl enable mongod
Then start the MongoDB service:
sudo systemctl start mongod
You can verify its status:
sudo systemctl status mongod
A success message indicates your MongoDB server is active. If everything checks out, you have completed the database portion of your MEAN stack.
Initial MongoDB Configuration
While MongoDB works out of the box, you can customize configurations in your /etc/mongod.conf
file. For example, you might want to enable authorization for security or alter network binding:
sudo nano /etc/mongod.conf
Adjust settings like bindIp
or enable authorization under the security
section. After changes, restart MongoDB to apply them:
sudo systemctl restart mongod
With MongoDB properly installed and configured, you are well on your way to a functioning MEAN environment. Next up is integrating Express.js to handle the application’s back-end logic.
Installing Express.js
Express.js is a minimalist back-end framework that runs on Node.js, enabling you to create robust server-side logic. It simplifies the process of managing routes, handling requests and responses, and rendering dynamic content. Since it works seamlessly with Node.js, installing Express.js typically involves using npm within your project’s directory.
Install Express Globally or Locally
While some developers prefer a global installation, a local installation within a specific project is often more manageable. Below is a straightforward local installation approach:
mkdir my-mean-app
cd my-mean-app
npm init -y
npm install express
After running these commands, you’ll have a new project folder that includes the dependencies specified in your package.json
. If needed, you can adjust version numbers or add additional modules, but the above steps provide a solid foundation for Express.js.
Create a Basic Express.js Server
To confirm Express.js is functioning, set up a simple server. Inside your project directory, create a file called server.js
:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express.js!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Save it and run:
node server.js
Navigate to http://localhost:3000
in your browser. If you see the message indicating “Hello from Express.js!”, your basic Express server is live and ready.
Angular CLI Setup
Angular is a front-end framework that streamlines the creation of interactive web applications. With data binding and two-way communication, it delivers a highly responsive user experience. The Angular Command Line Interface (CLI) further automates repetitive tasks, enabling developers to generate components, services, and modules seamlessly.
Install Angular CLI
Use npm to install the Angular CLI package globally:
sudo npm install -g @angular/cli
This global installation allows you to generate Angular projects anywhere on your system using the ng
command. Verify if the installation was successful:
ng version
Create a New Angular Project
Navigate to a directory of your choice, then create a new project:
ng new my-angular-app
You can name your project anything you prefer. As the CLI generates files, it will prompt you with configuration options such as routing and CSS pre-processors. Choose what best suits your needs, or use the defaults for simplicity.
Once the process is complete, move into the project folder and serve the application:
cd my-angular-app
ng serve --open
Angular CLI compiles and spins up a development server at http://localhost:4200
. Here, you’ll see the starter project working. You can modify components, add features, or incorporate third-party libraries according to your requirements.
Project Configuration
Once Node.js, MongoDB, Express.js, and Angular are in place, you can structure a MEAN application that synchronizes front-end and back-end operations. A typical layout includes separate folders for client (Angular app) and server logic (Express.js), unified by a shared configuration file or environment variables.
Sample Structure
mean-app/
|- server/
| |- server.js
| |- routes/
| |- controllers/
|- client/
| |- (Angular files)
|- package.json
This directory structure separates front-end and server-side files, reducing confusion. You might store environment-specific database and API configurations under server/config
or .env
files. Angular communicates with Express.js through RESTful endpoints. Express.js, in turn, interacts with MongoDB for data storage.
After structuring your project, you can unify it with scripts in package.json
ensuring a single command triggers server and client builds. This approach helps you manage large codebases effortlessly.
Testing the Stack
Ensuring your entire MEAN stack is functional is crucial before you proceed with in-depth development. It confirms that each segment—MongoDB, Express.js, Angular, and Node.js—works cohesively.
Basic Integration Test
1. Modify your Express.js server.js
to include a simple API that reads data from MongoDB:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/mean_app', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Define a sample schema
const TestSchema = new mongoose.Schema({
name: String
});
const TestModel = mongoose.model('Test', TestSchema);
app.get('/api/testdata', async (req, res) => {
try {
const items = await TestModel.find({});
res.json(items);
} catch (error) {
res.status(500).send(error);
}
});
app.listen(3000, () => {
console.log('MEAN stack test server running on port 3000');
});
2. In your Angular app (e.g., my-angular-app/src/app/app.component.ts
), call the endpoint:
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>Angular MEAN Test</h1>
<ul>
<li *ngFor="let item of items">{{ item.name }}</li>
</ul>
`
})
export class AppComponent {
items: any[] = [];
constructor(private http: HttpClient) {
this.http.get<any[]>('/api/testdata').subscribe(data => {
this.items = data;
});
}
}
3. Since Angular and Express might run separately, you have two options for integration:
- Proxy Configuration: Add a proxy in your Angular
proxy.conf.json
to forward calls from/api
tolocalhost:3000
. - Single Server Build: Serve Angular’s built files via Express.js. This entails building your Angular app for production and serving the
dist/my-angular-app
folder with Express on the same port.
With either approach, verifying data retrieval from MongoDB in your Angular interface confirms that all components of the MEAN stack are communicating effectively.
Troubleshooting Guide
Complex installations can lead to errors. Here are some typical issues and potential remedies:
- Port Conflicts: If Node.js or MongoDB fails to start due to port conflicts, identify the processes using those ports with a command like:
sudo lsof -i :3000
Then kill the process or switch to a free port.
- Firewall Restrictions: If external clients can’t access your application, check firewall settings:
sudo ufw status
Enable or open the necessary ports (3000, 4200, and 27017 for MongoDB default).
- npm Permission Errors: Running npm global installs might lead to permission issues. Use
sudo
(cautiously), or reconfigure npm to install packages at the user level as shown in a previous step. - Dependency Version Conflicts: Collisions between old and new dependencies can break your build. Remove
node_modules
and perform:npm install
to reinstall them from scratch.
- Service Fails to Start: Re-check your logs using:
sudo systemctl status mongod
and
journalctl -u mongod
for more clues.
Errors usually stem from simple misconfigurations. Diligently examining logs and confirming settings can help pinpoint the cause of most issues quickly.
Security Considerations
Although the MEAN stack is efficient, it’s still vital to put basic security measures in place. Here are a few foundational steps:
- Enable MongoDB Authentication: Modify
/etc/mongod.conf
to require credentials for database access. - Use HTTPS: Configure SSL/TLS so that sensitive data remains encrypted in transit.
- Sanitize User Input: Validate and sanitize incoming data to mitigate common threats such as injection attacks.
- Regularly Update Packages: Keep Node.js, MongoDB, Express.js, and Angular versions up to date to benefit from the latest security patches.
Addressing these aspects early not only protects your application but also safeguards user data.
Congratulations! You have successfully installed MEAN Stack. Thanks for using this tutorial for installing MEAN Stack on Ubuntu 24.04 LTS system. For additional help or useful information, we recommend you check the Ubuntu website.