Full Stack Software Developer

Running multiple websites on a VPS using docker and NGINX reverse proxy

It is possible to run multiple websites running on difference instances of docker using different ports. The NGINX server will listen on port 80 and forward to appropriate docker instance and port based on the domain name.

One approach of getting to this is to install NGINX server and manually configure this to forward to different ports based on domain name. All you have to do is create domain specific site config file in /etc/nginx/sites-available/ folder and then create a symbolic link of the same file at /etc/nginx/sites-enabled/ folder. Then restart the server and it should work on its own.

Another approach is to run the NGINX in a separate docker instance and have it listen on to port 80. In order for it to work, you have to create a docker network and make sure both the NGINX server docker instance and all other docker instances are running on the same network.

Joel Hans has written a good post about the whole process at this link.

But the basic of the whole process is to keep the network same and pass VIRTUAL_HOST environment variable with all other docker instances that hosts the web server. This variable is used to resolve and create necessary reverse proxy files by the jwilder/nginx-proxy.

Sample reverse-proxy.yml file:

version: "3.9"

services:
  reverseproxy:
    container_name: reverseproxy
    hostname: reverseproxy
    image: jwilder/nginx-proxy
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
    ports:
      - 80:80

networks:
  skynet:
    external:
      name: skynet

Sample webapp.yml file

version: "3.9"

services:
  webapp:
    container_name: webapp
    hostname: webapp
    image: httpd:2.4
    environment:
      VIRTUAL_HOST: webapp
    ports:
      - 8081:80

networks:
  skynet:
    external:
      name: skynet

The reverse proxy listens on port 80 and as soon as the matching virtual host of webapp is found it forwards it to http://webapp:8081.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.