Docker Compose: Setting up Nginx

08:02 pm, 11 February 2021| configuration| docker-compose, docker, ngninx,

Snippet to help setting up nginx for in your docker-compose setup

Before

We have 2 containers/services - backend and frontend running at 8000 & 3000 ports respectively

  • frontend -> http://localhost:3000
  • backend -> http://localhost:8000

After

We want the frontend to be accessible at localhost and backend at /api path

  • frontend -> http://localhost/
  • backend -> http://localhost/api

Configuration

Directory Structure

../
  backend/
  frontend/
  nginx/
    Dockerfile
    nginx.conf
  docker-compose.yml

docker-compose.yml

version: '3.6'
services:
  ...

  backend:
    image: django_project
    ports:
      - 8000:8000
    networks:
      - main
    ...

  frontend:
    image: react_project
    ports:
      - 3000:3000
    networks:
      - main
    ...

  nginx:
    container_name: my_nginx_container
    image: nginx
    # We will build our own nginx container/service
    build:
      # a folder "nginx" needs to exist in the same dir as docker-compose.yml
      context: nginx
     # nginx folder should have the dockerfile to build the nginx container
      dockerfile: Dockerfile
    ports:
      - "80:80"
    depends_on:
      # frontend & backend will be referenceable in nginx.conf for setting upstreams
      - backend
      - frontend
    networks:
      - main
    command: [nginx-debug, '-g', 'daemon off;']

networks:
  main:

Dockerfile

FROM nginx:stable-alpine

# we remove the default ngnix config
RUN rm /etc/nginx/conf.d/default.conf

# we replace it / copy our custom nginx config
ADD ./nginx.conf /etc/nginx/conf.d/nginx.conf

nginx.conf

upstream frontend_server {
  server frontend:3000;
}

upstream backend_server {
  server backend:8000;
}

server {

  listen 80;
  # domain = localhost
  server_name localhost;

  server_tokens off;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection 'upgrade';
  proxy_set_header Host $host;
  proxy_cache_bypass $http_upgrade;
  client_max_body_size 100M;

  # localhost will take to localhost:3000 or the frontend container
  location / {
      proxy_pass http://frontend;
  }

  # localhost/api will take to localhost:8000 or the backend container
  location /api {
    proxy_pass http://backend;

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_redirect off;
    proxy_connect_timeout       70s;
    proxy_send_timeout          86400;
    proxy_read_timeout          86400;
    send_timeout                86400;
  }

}

That's it!