Skip to main content

Deploy Sites and Enable HTTPS

Recently, I completed a personal project where I used Docker to deploy a database and NodeJS backend on AWS EC2. The frontend project was automatically deployed via Vercel.

Since Vercel deployment comes with SSL, I was required to add SSL when deploying the backend on AWS.

Previously, I obtained an SSL certificate for free via Tencent Cloud and set it to load via Nginx to enable HTTPS access as follows:

server {
    listen 443 ssl;

    ssl_certificate /etc/nginx/ssl/your_certificate.crt;
    ssl_certificate_key /etc/nginx/ssl/your_private_key.key;

    location / {
        proxy_pass <http://localhost:3000>;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

This time, I tried another method, Let’s Encrypt.

First, I added the following configuration to the /etc/nginx/conf.d/your-website.conf file.

server {
    listen 80;
    server_name your-domain-name.com;

    # Serve the static page
    location / {
        root /root/of/your/dist/folder;
        try_files $uri $uri/ /index.html;
    }

    # Serve the backend application
    location /api/v1 {
        proxy_pass <http://localhost:4000>; # Change it to your app's listening port
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

After saving, I executed the following commands for testing:

# reload nginx settings
sudo nginx -s reload

# restart nginx
sudo systemctl restart nginx

# test nginx settings
sudo nginx -t

Once everything was normal, I performed a series of installations as directed by my AI teacher:

sudo apt-get update
sudo snap install --classic certbot # could be different based on your system's PKM

After resolving your domain to the server address with your domain purchase provider, I started configuring with:

sudo certbot --nginx

I followed the instructions to make a series of settings. During this process, I encountered a small bug where the certificate could not be generated. After searching, I found that this was because the domain was just purchased and certbot could not find the DNS record. So, after waiting a while, I continued with the settings and it worked.

Update April 3, 2024

A minor episode:

After all configurations were completed, nginx was unable to access the root path due to lack of permissions.

My frontend dist directory is /home/ubuntu/project/dist. I tried to change the permissions and owner of the dist, project, and other directories, but it was ineffective.

I subsequently concluded that the ubuntu directory needed to have read and execute permissions added for others.

sudo chmod o+rx ubuntu