Skip to main content
  1. Posts/

Nginx Reverse Proxy With Multiple Containers and Certbot

·2 mins

A reverse proxy is a proxy that sits between the internal containers and the external clients that want to connect to it. A reverse proxy forwards the client requests to the appropriate container. I’ll be using Nginx as my reverse proxy becasue Nginx has a number of advcanced loadbalancing and security features.

In this blog post I’ll be seting up a server with two docker containers and a Nginx reverse proxy. The webservices running in the containers will have HTTPS enabled. For the Ssl I’ll be using certbot/letsencrypt.

First we need to SSH into our server. I have an Ubuntu server and it already comes with Docker and Nginx preinstalled. Docker is easy to install. If you don’t have Docker installed please check the Docker docs page for installation instructions.

For this post I will create two simple containers (these containers are create with the Nginx image. This has nothing to do with our reverse proxy that we will setup on the server itself).

docker run -it -d -p 1111:80 --name TestContainer1 nginx && docker run -it -d -p 2222:80 --name TestContainer2 nginx

After you have installed Nginx on the server it creates a default config page in /etc/nginx/sites-available/ called ‘default’. This file and the simlink needs to be removed:

rm /etc/nginx/sites-enabled/default && rm /etc/nginx/sites-available/default

Now we need to find out what the Ip addresses are of our containers:

docker container inspect TestContainer1 | grep IpAddress
docker container inspect TestContainer2 | grep IpAddress

So now we have the Ip addresses of our containers we can create the Nginx config files (change the server name, container ip and container port):

vim /etc/nginx/conf.d/TestContainer1.conf

server {
     	listen 80;
     	listen [::]:80;

     	location / {
     		proxy_pass http://IP_OF_THE_CONTAINER:CONTAINER_PORT;
     		proxy_buffering off;
     		proxy_set_header X-Real-IP $remote_addr;

Create a second config file in /etc/nginx/conf.d/ for the second container. Test your config files:

nginx -t

Make sure that your (sub)domains are pointing to your server and reload Nginx:

systemctl reload nginx

Browse to your domains to check if they are working.

Now we will setup HTTPS for the two webpages. Its very easy to setup HTTPS with certbot. Make sure that certbot is installed:

apt install snapd -y
snap install core
snap refresh core
snap install --classic certbot
ln -s /snap/bin/certbot /usr/bin/certbot

Run certbot. Certbot will automatically edit your config files and point to the certificate files:

certbot --nginx