deploy host node JS Express MongoDB locally website on AWS EC2 with free SSl Certificate

21 Sep 2024

deploy host node JS Express MongoDB locally website on AWS EC2 with free SSl Certificate

Setup EC2 with Debian OS

  • Ensure the following protocols are set up: SSH, HTTP, HTTPS, and MongoDB on port 27017.


Update and Upgrade Packages

  • sudo apt update
  • sudo apt upgrade


Install Node.js

  • Visit NodeSource and copy the Node.js CLI for installation.


Install PM2 Globally

  • sudo npm install pm2 -g


Install MongoDB


Allow MongoDB Compass Access

  • Edit MongoDB configuration:
  • sudo nano /etc/mongod.conf


Save the MongoDB Configuration

  • Exit and save the file using:
  • Ctrl + XYEnter


Restart MongoDB

  • sudo systemctl restart mongod


Check MongoDB status:

  • sudo systemctl status mongod


Check MongoDB Compass Login

  • Use the following connection string:
  • mongodb://ec2-ip:27017


Install Nginx

  • sudo apt install nginx


Change Ownership for /var/www Directory

  • sudo chown admin /var/www to allow file permissions.


Setup Nginx Reverse Proxy

  • Edit the Nginx configuration:
  • sudo nano /etc/nginx/sites-available/default


Nginx Configuration Example

server {
    listen 80;

    server_name _;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}


Save the Nginx Configuration

  • Exit and save the file using:
  • Ctrl + XYEnter


Restart Nginx

  • sudo systemctl restart nginx


Check Nginx status:

  • sudo systemctl status nginx


Get SSL on Nginx

Install Certbot and Nginx plugin:

  • sudo apt install certbot python3-certbot-nginx


Obtain SSL certificates:

  • sudo certbot --nginx -d demo.com -d www.demo.com


Test SSL certificate renewal:

  • sudo certbot renew --dry-run


Handle SSL Errors (if any)

  • If there are SSL errors, edit the Nginx configuration:
  • sudo nano /etc/nginx/sites-available/default


Nginx SSL Configuration Example

server {
    listen 80;
    server_name demo.com www.demo.com;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # Redirect www to non-www
    if ($host = 'www.demo.com') {
        return 301 http://demo.com$request_uri;
    }

    # Other necessary configurations
}


Restart Nginx and Check Status

  • sudo systemctl restart nginx
  • sudo systemctl status nginx


Notes and Source Code