Setup HTTPS For Nginx On AWS EC2 Linux Instance Using Docker And Certbot

Prerequisite for this requirement

1. EC2 Linux Machine. Install docker and git in it by using the following commands

After launching the instance, run the below command to install docker and git.

sudo yum update

sudo yum install docker
sudo yum install git

wget https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)
sudo mv docker-compose-$(uname -s)-$(uname -m) /usr/local/bin/docker-compose
sudo chmod -v +x /usr/local/bin/docker-compose

sudo systemctl enable docker.service
sudo systemctl start docker.service
sudo usermod -a -G docker ec2-user

sudo reboot

2. Have a domain in route53 which should point to my IP address running on an AWS EC2 instance (Linux).

PFB steps to install the SSL certificate in EC2 Linux Machine

1. Check docker and git are installed and also clone the code from my repo

2. First run the nginx with the command

docker-compose up — build nginx

This will start the nginx server. Now try to browse the application with the domain name or with IP address. This should show you the nginx home page with not secured symbol

3. Now in another terminal, run the letsencrypt container with the below command

docker-compose -f docker-compose-cert.yaml up — build

If things work fine, you will see like this.

Generated certificates will be available under ‘/etc/letsencrypt/<yourdomainname>’ directory on your machine

4. Enable HTTPS

Stop running the nginx container in terminal 1, and change the nginx config

Above, we have a very simple nginx config file which is serving the application on two ports 80 and 443, for HTTP and HTTPS respectively. If anyone tries to access the application over the HTTP protocol, it would be redirected to HTTPS as defined by the redirect and here we have the configuration of our certificates.

Now run the nginx container again but with the -d flag this time.

docker-compose up — build -d nginx

Now navigate to your domain and you should find an nginx 404 page served over HTTPS.

We Served the application over HTTPS. Now you can deploy your react/angular/api project in this Linux machine and serve with HTTPS😊

Notes to remember about lets encrypt:

Be sure to learn about their rate limit of Lets encrypt SSL certificates. Like for the same domain, you cannot get certificates more than 20 times per week. If you exceed the limit it will block your domain and for every 90 days, we need to renew your certificate. You can setup a cron job in the machine that can run every day and renew the certificates. Once the certificate is renewed, we need to reload the nginx server to make use of the renewed certificate.


Similar Articles