How To Deploy your Backend Server to MongoDB and Host Using Digital Ocean

The Confused Creative
6 min readJun 9, 2024

--

By the end of this guide, you’ll clearly understand how to set up your backend environment, making your application accessible to users worldwide with high performance and reliability.

Deploying a backend server involves several critical steps, from setting up your database with MongoDB Atlas to hosting the application server on a robust platform like Digital Ocean. This guide provides a straightforward, step-by-step approach to deploying your backend infrastructure, ensuring your application is scalable and secure.

What you’ll need to get started:

  • MongoDB
  • Digital Ocean
  • Cloudflare
  • Namecheap
  • FileZilla
  • Frontend build directory ready for deployment.

Buy Your Domain from Namecheap

  • Visit Namecheap: Go to Namecheap’s website and search for your desired domain name. Purchase the domain if it is available.

Set Up Cloudflare

  • Create a Cloudflare Account: Register for an account at Cloudflare.
  • Add Your Site to Cloudflare: Input your domain name and allow Cloudflare to scan your DNS records.
  • Update DNS on Namecheap: Cloudflare will provide you with two nameservers. Log into your Namecheap account, navigate to the domain’s DNS settings, and replace the existing nameservers with the ones provided by Cloudflare.
  • Get Your Domain Running: To get your domain name running, you’ll have to add it to the DNS records. This way your server is connected to your domain.
Type: A 
Name (required): Use @ for root
IPv4 address (required): Droplet IP
Proxied Status: Proxied
TTL: Auto

Create a MongoDB Atlas Account

  • Sign Up for MongoDB Atlas: Go to MongoDB Atlas and create an account.
  • Create a Cluster: Once logged in, create a new cluster. Choose a cloud provider and a region close to where you expect your users or server to be.
  • Create a Collection: In your cluster, create a new database and within it, create collections as per your data organization needs.
  • Network Access: Go to the “Network Access” settings and add the IP address of your Digital Ocean droplet to ensure that only your server can connect to the database.
  • Database User: Create a database user with read and write privileges. Note the username and password as they will be needed for the connection string.

Set Up Digital Ocean Droplet

  • Create a Droplet: Log into Digital Ocean and create a new droplet. Choose an image (Ubuntu, CentOS, etc.), plan, and datacenter region.
  • Access Droplet: Once your droplet is set up, access it using SSH with the IP address provided by Digital Ocean.

Deploy Backend Server

  • Upload Your Code: You can use SFTP, SCP or FileZilla to upload your server code to the droplet.
  • Environment Variables: Set up your environment variables in a .env file on your droplet, including MONGO_URI which should look like this:
MONGO_URI=mongodb+srv://username:password@clusterURL/databaseName?retryWrites=true&w=majority
  • Install Dependencies: Run npm install or yarn to install necessary packages.
  • Start the Server: Use a process manager like PM2 to start your server and to ensure it stays active across restarts and crashes. Example command:
pm2 start server.js

Verify and Monitor

  • Test the Connection: Ensure your backend can connect to MongoDB and is accessible over the internet.
  • Set Up Monitoring on Cloudflare and Digital Ocean: Utilize tools provided by both platforms to monitor traffic and performance.

This setup ensures that your backend is securely hosted on Digital Ocean with a MongoDB database hosted on Atlas, using Cloudflare for additional security and performance optimizations. If you encounter any specific errors during setup, check logs for more details and adjust configurations as necessary.

SSL/TLS Configuration

  • Use Let’s Encrypt to set up SSL/TLS certificates for secure HTTP connections using Certbot.
  • Configuration for redirecting HTTP traffic to HTTPS was implemented in the Nginx settings.

Install FileZilla

This will help you when adding build files, adding files or changing code in your droplet. To activate it

  • Host: droplet Ip
  • Username: root (or whatever you chose)
  • Password: password for your droplet that you created
  • Port: 22

How to update your server

Whenever a change is made to your backend:

  • Compress the whole folder excluding node_modules.
  • Use FileZilla to navigate to /srv.
  • Drop the zip file in /srv.

Go to the Digital Ocean droplet terminal:

  • Navigate to /srv using cd .. to get to the root folder and then cd /srv to get to the services folder.
  • Unzip the compressed file using unzip fileName.
  • Run npm install to install dependencies.
  • Restart the backend server using pm2 restart appName.
  • Check the logs using pm2 logs appName.

How to Add More Sub-domains

For enhanced organization and functionality, you can assign specific subdomains to different parts of your application, such as separating the main app, the API, and the admin panel. This setup simplifies access and enhances security by segregating the access points according to usage. Here’s how to configure these subdomains:

You can change the URL your domain points to from test.com to api.test.com. This way your API has a different URL, your main app uses the main URL and you can add more if you have an admin app too.

DNS Configuration

Firstly, update your DNS settings to point the new subdomains to your server’s IP address. Here’s how you can add them:

For an API:

Type: A
Name: api (This will create the subdomain api.test.com)
IPv4 address: [Your Droplet’s IP]
Proxied Status: Proxied (to take advantage of Cloudflare's security and performance features)
TTL: Auto (Cloudflare will manage the TTL)
For an Admin Panel:

Type: A
Name: admin (This will create the subdomain admin.test.com)
IPv4 address: [Your Droplet’s IP]
Proxied Status: Proxied
TTL: Auto

Update Web Server Configuration

After setting up your DNS records, configure your web server to recognize and correctly route traffic for these subdomains:

  • Navigate to your web server’s configuration directory (usually /etc/nginx/sites-available/ for Nginx).
  • Create or edit a configuration file for each subdomain.
  • Here’s a basic example of an Nginx server block:
server {
listen 80;
server_name api.test.com;

location / {
proxy_pass http://localhost:API_PORT;
include /etc/nginx/proxy_params;
}
}

server {
listen 80;
serveried security policies.server_name admin.test.com;

location / {
proxy_pass http://localhost:ADMIN_PORT;
include /etc/nginx/proxy_params;
}
}
  • Enable these configurations by linking them in /etc/nginx/sites-enabled/.
  • Check the configuration and reload Nginx:
sudo nginx -t
sudo systemctl reload nginx

Obtain SSL Certificates

Ensure that all subdomains are secured with SSL certificates. You can easily generate them using Let’s Encrypt:

sudo certbot --nginx -d api.test.com -d admin.test.com

Testing

Finally, verify that the subdomains are correctly pointing to your server:

  • Use ping, dig, or visit the subdomains in a browser to check their active status.
  • Ensure SSL certificates are valid and correctly installed by accessing https://api.test.com and https://admin.test.com.

By following these steps, you effectively manage multiple aspects of your application through dedicated subdomains, each configured for a specific function.

Deploy Your Frontend Application to Your Droplet

You can also deploy your frontend application to your Digital Ocean Droplet. You can upload files using FileZilla, a popular FTP client, and then manage the files via the Droplet console (SSH). Here’s a detailed step-by-step guide:

Prerequisites:

  • Your Digital Ocean Droplet set up and running.
  • SSH access to your Droplet.
  • FileZilla installed on your local machine.
  • Your frontend build directory ready for deployment.

Preparing Your Droplet

  1. SSH into your Droplet:
  • Open a terminal or command prompt.
  • Use the SSH command to connect:
ssh root@your_droplet_ip
  • Enter your password or authenticate with your SSH key.

2. Install a Web Server (if not already installed):

  • For Nginx, use:
sudo apt update sudo apt install nginx
  • After installation, start and enable Nginx:
sudo systemctl start nginx sudo systemctl enable nginx

Step 2: Uploading Files Using FileZilla

  1. Open FileZilla and connect to your Droplet:

— Go to File > Site Manager > New Site.

— Set the following:

  • Host: Your Droplet’s IP address.- Port: 22 (for SFTP).
  • Protocol: SFTP — SSH File Transfer Protocol.
  • Logon Type: Choose ‘Normal’ and enter your SSH credentials.

— Click Connect.

2. Upload Your Files:

  • In the Remote site area, navigate to /var/www/html. This is a common directory to serve web files from.
  • On your local site, navigate to where your frontend build directory is located.
  • Drag and drop the build directory from your local site to the remote site in FileZilla.

Step 3: Configuring Nginx to Serve Your Application

  1. Create a Configuration File for Your Website:
  • Navigate to Nginx’s sites-available directory:
cd /etc/nginx/sites-available/
  • Create a new configuration file:
nano yourdomain.com
  • Add the following configuration:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
    root /var/www/html/build;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}

2. Enable the Website:

  • Link your configuration file to the sites-enabled directory:
ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/
  • Check for syntax errors:
nginx -t
  • Reload Nginx to apply changes:
systemctl reload nginx

Step 4: Testing Your Deployment

  • Open a web browser and navigate to http://yourdomain.com to see if your front-end application is being served correctly.

Following these steps, you upload your frontend application using FileZilla and configure Nginx to serve it from your Digital Ocean Droplet. This setup ensures that your application is accessible via the web and properly managed via secure protocols.
Let me know if you have any questions in the comment section.

--

--

The Confused Creative
The Confused Creative

Written by The Confused Creative

Multifaceted Creative. MERN stack Developer. Certified PT

No responses yet