ECL-94
ECL-94

Reputation: 107

How to configure nginx with docker-compose?

I have a simple app of 3 containers which all run in the same AWS EC2 server. I want to configure Nginx to act as a reverse-proxy however I'm pretty new with Nginx and don't know how to set the conf file correctly.

Here is my docker-compose:

version: "3"
services:

  nginx:
    container_name: nginx
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./conf/nginx.conf:/etc/nginx/nginx.conf

  frontend:
    container_name: frontend
    image: myfrontend:image
    ports:
      - "3000:3000"

  backend:
    container_name: backend
    depends_on:
      - db
    environment:
      DB_HOST: db
    image: mybackend:image
    ports:
      - "8400:8400"

  db:
    container_name: mongodb
    environment:
      MONGO_INITDB_DATABASE: myDB
    image: mongo:latest
    ports:
      - "27017:27017"
    volumes:
      - ./initialization/db:/docker-entrypoint-initdb.d
      - db-volume:/data/db

volumes:
  db-volume:

The backend fetches data from the database and sends it to be presented by the frontend.

Here is my nginx.conf file:

events {
  worker_connections  4096;  
}

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

   server_name myDomainName.com;

   location / {
       proxy_pass http://frontend:3000/;
       proxy_set_header Host $host;
   }

   location / {
      proxy_pass http://backend:8400/;
      proxy_pass_request_headers on;
    }

 }
}

How can I set nginx to serve the frontend and backend containers?

Upvotes: 2

Views: 9905

Answers (1)

Al-waleed Shihadeh
Al-waleed Shihadeh

Reputation: 2855

You can use the below Nginx configs to solve your issue

events {
  worker_connections  4096;  
}

http {

 server {
    listen       80 default_server;
    server_name  frontend.*;

    location / {
        resolver 127.0.0.11 ipv6=off;

        set $target http://frontend:3000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass $target;
    }
  }

  server {
    listen       80;
    server_name  backend.*;

    location / {
        resolver 127.0.0.11 ipv6=off;

        set $target http://backend:8400;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass $target;
    }
  }
}

Nginx will be serving the backend and frontend on different domain names, with the below, etc hosts you will be able to get access to the services on the defined domain names

127.0.0.1 backend.me frontend.me

Upvotes: 0

Related Questions