Cronspam

Trials and Tribulations with Technology


Run Nginx with Docker

Docs: https://hub.docker.com/_/nginx/

I want to run multiple blogs on the same Lightsail instance.  To do this, a reverse-proxy is needed to direct the incoming requests for different URLs to the appropriate Ghost instances to handle them. I'm using Nginx as my reverse-proxy, and I'm using Docker to run it.

The Hello World version

Connect to your Lightsail instance and create paths for the Nginx configuration:

mkdir -p ~/websites/nginx/conf.d
mkdir -p ~/websites/nginx/includes

Create a  ~/websites/nginx/conf.d/default.conf configuration for Nginx - I copied this one from within the Docker container, it's pretty simple:

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

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Then launch the Docker image for Nginx. This will automatically pull the Docker image from Dockerhub:

docker run -d \
  --name nginx \
  --network=host \
  -v /home/ec2-user/websites/nginx/conf.d:/etc/nginx/conf.d:ro \
  nginx:1

To reload Nginx configuration without needing to restart the container, send it a HUP signal:

docker kill -s HUP nginx

Otherwise, just restart the Nginx container:

docker restart nginx

NOTE: If you still have the Ghost Docker container running, there will be a port conflict on :80 as both that Ghost instance this Nginx instance are trying to manage :80 at the same time. You'll need to shut down the Ghost instance while setting up Nginx.

Using docker-compose

Create a ~/websites/nginx/nginx.yaml Docker compose file to configure the Docker container:

version: '3.1'

services:

  nginx:
    container_name: nginx
    image: nginx:1
    restart: always
    network_mode: host
    volumes:
      - /home/ec2-user/websites/nginx/conf.d:/etc/nginx/conf.d
      - /home/ec2-user/websites/nginx/includes:/etc/nginx/includes:ro
      - /home/ec2-user/websites:/var/websites:ro

Launch the Nginx Docker container using docker-compose:

docker-compose -f ~/websites/nginx/nginx.yaml up --detach