This setup is tested on Rad Web Hosting, so it should work fine on other VPS, cloud servers running Ubuntu 20.04 or Ubuntu 18.04.

Prerequisites

    Sponsored
  • A Ubuntu server with sudo access (I am using Ubuntu VPS with 20.04 installed)
  • A domain name pointed to your server.

Initial Server Setup

Start by updating the server packages to the latest available.

sudo apt update
sudo apt dist-upgrade -y

Now you can proceed to setup MERN stack.

Install MongoDB

Here we will install MongoDB Community Edition with LTS using the apt package managed. The current latest version of MongoDB at the time of this article is 5.0.5.

You may need to install gnupg for importing the key.

 sudo apt install gnupg

Import the public key using the following command.

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

Add the MongoDB repository to the sources list.

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

Update the packages and install MongoDB.

sudo apt update
sudo apt install -y mongodb-org

Once the installation is completed enable MongoDB to start at system startup.

sudo systemctl enable mongod

Start MongoDB server.

sudo service mongod start

You can view the status using the following command.

sudo service mongod status

Output
● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-01-16 22:08:26 UTC; 7h ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 1942 (mongod)
     Memory: 164.5M
     CGroup: /system.slice/mongod.service
             └─1942 /usr/bin/mongod --config /etc/mongod.conf

Jan 16 22:08:26 staging systemd[1]: Started MongoDB Database Server.

Configure MongoDB

Now we can secure MongoDB, configure MongoDB to accept remote connections and also create a new database.

See also  What is MLOps?

Secure MongoDB

Edit MongoDB config file.

sudo nano /etc/mongod.conf

Scroll down to the security section #security and uncomment it and enable authorization. The final edit should look as below.

security:
  authorization: enabled

Enable Remote Connections

To enable remote connections you need to edit the same file and add your internal or private IP to the network interfaces. Your configuration should look like the one below.

net:
  port: 27017
  bindIp: 127.0.0.1,10.128.10.1

Replace 10.128.10.1 with your IP address.

Open firewall if any for the port 27017.

Restart MongoDB.

sudo systemctl restart mongod

Confirm if MongoDB is allowing remote connections using the following command.

sudo lsof -i | grep mongo

You should receive an output similar to the one below.

mongod 1942 mongodb 11u IPv4 31550 0t0 TCP instance_name.c.project_id.internal:27017 (LISTEN)
mongod 1942 mongodb 12u IPv4 31551 0t0 TCP localhost:27017 (LISTEN)

Create MongoDB Admin User

Connect to MongoDB shell using mongosh command.

mongosh

Change to admin database.

use admin

Create admin user with all privileges and setup password.

db.createUser({user: "admin" , pwd: passwordPrompt() , roles: [{ role: "userAdminAnyDatabase" , db: "admin"}]})

Enter password when prompted.

Enter exit to exit the shell.

Now you can use the following connection string to connect to MongoDB.

mongodb://admin:password@External-IP:27017/database

Install Node.js with NVM

We will use Node Version Manager (NVM) to install Node.js. With this you can easily with between different Node.js versions.

Download and run the NVM installation script using wget.

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

Now load the nvm command to current shell session.

source ~/.bashrc

To list all available Node.js versions you can use the following command.

nvm ls-remote

Install the Node.js version you need with the below syntax.

Sponsored
nvm install v16.13.2

Once installed you can check Node.js and NPM versions.

node -v
v16.13.2

npm -v
6.14.13

Install React.js

Install and build frontend React.js using npx command.

Navigate to the folder where you want to install React app and execute the following command.

npx create-react-app frontend

This will take some time to install all React packages. Once the installation is completed you will see a frontend folder created with all basic React scripts.

Navigate in to frontend directory and trigger the build using npm.

cd frontend
npm run build

This will create a static output with HTML, CSS and JS files for your frontend.

You can point your Nginx web server to this build directory to serve your frontend.

Install Express.js

Install express generation using the npx command.

npx express-generator

Once the installation is completed create your backend application using express command.

cd ~/
express backend

Now your Express should be created. You can install all node modules and start Express server using PM2 in background as mentioned in the below section.

cd backend
npm install

Setup PM2 to Run Node.js in Background

PM2 is a Node Process Manager which is very useful to start Node servers in background.

Navigate to your Express application and execute the following command.

cd ~/backend
pm2 start npm --name "backend" -- start

Now your Express server is started in the background and listening on port 3000.

Configure PM2 to start Express application at startup.

pm2 startup

You will be provided a long command to execute. Once the command is executed you can save the settings.

pm2 save

Next you can configure Nginx reverse proxy over this port on a subdomain or a subfolder as per your wish.

Install Nginx and Configure it

Nginx is one of the best web server to work with Node.js based applications.

Install Nginx.

sudo apt install nginx

Remove default configurations

sudo rm /etc/nginx/sites-available/default
sudo rm /etc/nginx/sites-enabled/default

Create new Nginx configuration

sudo nano /etc/nginx/sites-available/application.conf

Paste the following. In this configuration we are pointing the main domain path to the build output directory of React.js application and the /api path for the Express.js application.

server {
     listen [::]:80;
     listen 80;

     server_name domainname.com www.domainname.com;

     root /home/cloudbooklet/backend/build/;
     index index.html;

     location / {
         try_files $uri $uri/ =404;
     }

     location /api/ {
         proxy_pass http://127.0.0.1:3001;
         proxy_http_version 1.1;
         proxy_set_header Connection '';
         proxy_set_header Host $host;
         proxy_set_header X-Forwarded-Proto $scheme;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $remote_addr;
    }
}

Save and exit the file.

Enable your configuration by creating a symbolic link.

sudo ln -s /etc/nginx/sites-available/application.conf /etc/nginx/sites-enabled/application.conf

Check your Nginx configuration and restart Nginx

sudo nginx -t
sudo service nginx restart

Install Let’sEncrypt SSL

We can use Certbot to install free Let’s Encrypt SSL certificate for your domain.

sudo apt install python3-certbot-nginx

Execute the following command to install certificate and configure redirect to HTTPS automatically.

sudo certbot --nginx --redirect --agree-tos --no-eff-email -m youremail@mail.com -d domain.com -d www.domain.com

Now you should receive SSL certificate and it will be configured automatically.

Setup auto renewal.

sudo certbot renew --dry-run

Now you can look up your domain in your browser to see the output.

Conclusion

Now you have learned how to install and setup MERN stack with Nginx on Ubuntu 20.04.