How to Setup a Nginx Reverse Proxy With Let's Encrypt for Microservices

Share on:

Let’s say one of your micro services is running on http://localhost:3000
If you already have a nginx service running on the server, create a server block like this:

1vim /etc/nginx/sites-available/domain.com.conf

Grab this content to paste in:

 1server {
 2
 3        server_name domain.com;
 4
 5        root /var/www/html;
 6        index index.html;
 7
 8        location / {
 9                proxy_pass http://localhost:3000;
10                proxy_http_version 1.1;
11                proxy_set_header Upgrade $http_upgrade;
12                proxy_set_header Connection 'upgrade';
13                proxy_set_header Host $host;
14                proxy_cache_bypass $http_upgrade;
15        }
16
17}

Make a link of the config file:

1sudo ln -s /etc/nginx/sites-available/domain.com.conf /etc/nginx/sites-enabled/

Check the validity of your config file with this command

1sudo nginx -t

Now that it went fine, you will be able to see your public domain will be showing your landing page or something like that.
It’s time to secure your service with Let’s Encrypt (Let's just assume that the server is running Ubuntu 18.04 Bionic for simplicity):

1apt-get update
2apt-get install software-properties-common
3add-apt-repository universe
4add-apt-repository ppa:certbot/certbot
5apt-get update
6apt-get install certbot python-certbot-nginx
7certbot --nginx

Now, you will have to configure a cron job for auto-renewing the received certificates.

1certbot renew --dry-run
2crontab -e

Grab this code followed by an empty line

10 0,12 * * * python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew
2

It seems you did an awesome job! 😉
A Bonus Tip: Nginx Purging - Right Way

1apt purge nginx nginx-common nginx-full

On CentOS 7/8, you need to configure SELinux as well like so:

1setsebool -P httpd_can_network_connect on

Happy coding! 😎