Setup MERN Stack on Ubuntu in Azure/AWS/GCP

Setup and install MERN stack on Ubuntu 22.04 in the cloud on Azure, AWS or Google GCP.  MERN stack includes MongoDB, Express.js, Vue.js, and Node.js. Together, these technologies form a full-stack JavaScript framework used to build dynamic, responsive web applications. MongoDB serves as the NoSQL database, Express.js provides the web server framework, Vue.js creates the frontend user interface, and Node.js handles the server-side logic. 

Cloud MERN Stack

MERN Stack Azure

MERN Azure

Deploy MERN Stack on Ubuntu 22.04 in Azure

MERN Stack AWS

Coming soon…

MERN Stack GCP

Coming soon…

Getting Started with MERN Stack

Once your MERN server has been deployed, the following links explain how to connect to a Linux VM:

 

 

Once connected and logged in, the following section explains how to start using MERN Stack.

How to Use MERN Stack (MongoDB, Express, Vue.js, Node.js) After Deployment

Once you’ve deployed MERN stack and logged in, you can start building and deploying web applications that use MongoDB, Express.js, Vue.js, and Node.js. This tutorial will guide you through creating a basic MERN application to get started.

Step 1: Create a New Project Directory

First, create a directory for your new MERN project:

				
					mkdir mern-app
cd mern-app

				
			

Step 2: Initialize a Node.js Project

To start the Node.js project, initialize it with npm:

				
					npm init -y

				
			

This command creates a package.json file that tracks dependencies and scripts for the project.

Step 3: Install Express.js in the Project

Next, install Express.js and CORs, the web framework that will handle HTTP requests and APIs in your backend:

Express server will connect to MongoDB. We will use Mongoose, a popular MongoDB library for Node.js, to interact with the database.

				
					npm install express cors mongoose

				
			

Once installed, create a basic Express server.

 

  1. Create a file named server.js:
				
					touch server.js

				
			

2. Edit server.js 

				
					sudo nano server.js
				
			

Add the following content:

Note: Replace the ip address with your server ip address under ‘Connect to MongoDB”.

				
					const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const Item = require('./models/Item');
const app = express();
const port = 5000;

// Middleware for parsing JSON
app.use(express.json());

// Enable CORS to allow requests from any origin
app.use(cors({
    origin: '*',  // You can restrict this to specific IPs/domains later
}));

// Connect to MongoDB using the local IP address
mongoose.connect('mongodb://10.1.0.4:27017/mern-vue-app')
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.error('MongoDB connection error:', err));

// Basic Route
app.get('/', (req, res) => {
    res.send('Hello World from Express.js');
});

// GET All Items
app.get('/items', async (req, res) => {
    try {
        const items = await Item.find();
        res.json(items);
    } catch (err) {
        res.status(500).send('Server error: ' + err);
    }
});

// POST Add Item
app.post('/items', async (req, res) => {
    try {
        const newItem = new Item({
            name: req.body.name,
        });
        const savedItem = await newItem.save();
        res.json(savedItem);
    } catch (err) {
        res.status(500).send('Error saving item: ' + err);
    }
});

// Start the server and listen on all interfaces
app.listen(port, '0.0.0.0', () => {
    console.log(`Server running on port ${port}`);
});

				
			

Save and exit

This creates a basic Express server that listens on port 5000 and responds with “Hello World from Express.js” when accessed.

Step 4: Setup MongoDB

Lets Create the MongoDB Model (Item.js) inside our MERN project:

 

  1. In a new folder models, create a file called Item.js:
				
					mkdir models
cd models
sudo touch Item.js
sudo nano Item.js
				
			

2. Paste the following into Item.js

				
					const mongoose = require('mongoose');

const ItemSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
});

module.exports = mongoose.model('Item', ItemSchema);


				
			

Save and Exit

 

Navigate back to the mern-app directory

Step 5: Configuring MongoDB to Accept External Connections

  1. Edit MongoDB configuration file (mongod.conf):
				
					sudo nano /etc/mongod.conf

				
			

2. Modify the bindIp configuration to allow connections from all interfaces (0.0.0.0), or just the local IP:

				
					net:
  bindIp: 0.0.0.0  # Allows connections from any IP address

				
			

Save and exit

3. Restart MongoDB:

				
					sudo systemctl restart mongod

				
			

4. Verify MongoDB is running

				
					sudo systemctl status mongod
				
			

5. Start Express Server

Navigate back to mern-app folder and run the following :

				
					node server.js
				
			

Now if you access http://ServerIPAddress:5000 You should see Hello World from Express.js

Step 6: Create a Vue.js Frontend

Now, let’s create a simple Vue.js frontend to interact with the Express server.

 

  1. Create the Vue.js project: In your project directory, run the Vue CLI to create a new Vue.js frontend:
				
					vue create frontend

				
			

2. Navigate to the frontend folder and serve the Vue app:

				
					cd frontend

				
			

3. Install Axios for making HTTP requests:

				
					npm install axios

				
			

Modify the Vue app to fetch data from the Express API:

 

  • Open the src/components/HelloWorld.vue file and replace with the following so it will fetch items that we will create later:
				
					sudo nano src/components/HelloWorld.vue
				
			

Replace IP address with your servers local ip address.

				
					<template>
  <div>
    <h1>Items from MongoDB:</h1>
    <ul>
      <li v-for="item in items" :key="item._id">{{ item.name }}</li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items: []
    };
  },
  created() {
    axios.get('http://10.1.0.4:5000/items')  // Use the public IP
      .then(response => {
        this.items = response.data;
      })
      .catch(error => {
        console.error('Error fetching items:', error);
      });
  }
};
</script>

				
			

Start Vue App

 

Make sure you’re still in the frontend folder

				
					npm run serve
				
			

Also make sure Express is running.

 

Open a 2nd terminal session in order to run. Run from your /mern-app/ directory:

				
					node server.js
				
			

Test MongoDB with Postman or Curl

  1. Now open a 3rd terminal session and run the following commans:
				
					curl -X POST http://localhost:5000/items -H "Content-Type: application/json" -d '{"name":"Item 123456"}'

				
			
				
					curl -X POST http://localhost:5000/items -H "Content-Type: application/json" -d '{"name":"Item ABC"}'

				
			

2. To get all items:

				
					curl http://localhost:5000/items

				
			

3. Access the Vue app: Open your browser and visit http://privateipaddress:8080 to see the list of users fetched from the backend.

MERN Documentation / Support

For further documentation and tutorials refer to the official documentation at:

 

MongoDB Community: https://www.mongodb.com/docs/manual/ 

 

Express.js: https://expressjs.com/

 

React.js: https://react.dev/

 

Nodejs: https://nodejs.org/docs/latest/api/

Firewall Ports

The MERN stack uses the following ports by default for its components:

 

1. MongoDB (Database):

 

  • Default Port: 27017
  • Purpose: MongoDB listens on port 27017 for incoming connections to the database. This is the port where your backend (Node.js/Express) connects to MongoDB to perform CRUD operations.

 

2. Express.js (Node.js Backend):

 

  • Default Port: Typically 3000 or 5000 (configurable)
  • Purpose: Express.js runs on a port to handle HTTP requests and serve responses. This is where your backend application listens for API requests.
  • Developers often use ports 3000 or 5000 during development, but this is configurable and can be changed to any port as needed.

 

3. Vue.js (Frontend):

 

  • Default Port: 8080 (configurable)
  • Purpose: Vue.js, when running in development mode, typically runs on port 8080 to serve the frontend of the application.
  • This port is used to load the frontend interface, which interacts with the backend API.

 


 

Typical Development Environment Setup:

 

  • MongoDB on port 27017
  • Express.js (Node.js backend) on port 5000
  • Vue.js frontend on port 8080

 

You can modify the ports for each of these components in their respective configuration files if needed.

 

Summary of Default Ports:

 

  • MongoDB: 27017
  • Express.js: 3000 or 5000
  • Vue.js: 8080

 

These ports are commonly used in a development setup but can be customized to suit your environment.

The links below explain how to modify / create firewall rules depending on which cloud platform you are using.

 

To setup AWS firewall rules refer to – AWS Security Groups

To setup Azure firewall rules refer to – Azure Network Security Groups

To setup Google GCP firewall rules refer to – Creating GCP Firewalls

Disclaimer: This software listing is packaged by Cloud Infrastructure Services. The respective trademarks mentioned in the offering are owned by the respective companies, and use of them does not imply any affiliation or endorsement. The license comes with a “no warranty” clause, meaning the software is provided “as-is” without any guarantees or liability for issues that may arise.

Avatar for Andrew Fitzgerald
Andrew Fitzgerald

Cloud Solution Architect. Helping customers transform their business to the cloud. 20 years experience working in complex infrastructure environments and a Microsoft Certified Solutions Expert on everything Cloud.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x