NGINX Reverse Proxy with Docker

วิธีการทำ Reverse Proxy Nginx ด้วย Docker

nginx-reverse-proxy.png?w=920


ก่อนอื่นจะมี folder ประมาณนี้

---| app1/
   |--- index.js
   |--- package.json
   |--- Dockerfile
---| app2/
   |--- index.js
   |--- package.json
   |--- Dockerfile
---| /nginx
   |--- default.conf

App1

---| app1/
   |--- index.js
   |--- package.json
   |--- Dockerfile
  • index.js
const express = require('express')
const app = express()

app.get('/',(req,res)=>{
    res.send("Hello App1")
})

app.listen(3001)
  • Dockerfile
FROM node:12

WORKDIR /app
COPY . /app

CMD ["node","index.js"]

start app1

$ cd app1
$ docker build -t app1 .
$ docker run -d -p 3001:3001 --name app1 app1

App2

- app1/
  - index.js
  - package.json
  - Dockerfile
  • index.js
const express = require('express')
const app = express()

app.get('/',(req,res)=>{
    res.send("Hello App2")
})

app.listen(3002)
  • Dockerfile
FROM node:12

WORKDIR /app
COPY . /app

CMD ["node","index.js"]
  • start app1
$ cd app2 
$ docker build -t app2 .
$ docker run -d -p 3002:3002 --name app2 app2

จากนั้นทำ Create network เพื่อให้ ทั้งสองหากันเจอ

$ docker network create reverse-proxy

connect network ที่สร้าง

$ docker network connect reverse-proxy app1
$ docker network connect reverse-proxy app2

ลอง Connect กันดู

$ docker exec -it app1 curl http://app2:3002
...
Hello App2

$ docker exec -it app2 curl http://app1:3001
...
Hello App1

Nginx

- nginx/
  - default.conf
  • Set config nginx
server {
    listen       80;
    server_name  localhost;

    location /app1 {
        proxy_pass http://app1:3001/;
    }
    location /app2 {
        proxy_pass http://app2:5000/;
    }
}
  • run nginx
$ cd nginx
$ docker run -d -p 80:80 --network reverse-proxy -v $PWD/default.conf:/etc/nginx/conf.d/default.conf \
--name nginx nginx

ลอง curl หรือเปิดผ่าน browser

$ curl localhost/app1
...
Hello App1
$ curl localhost/app2
...
Hello App2

Success