ローカル開発環境でプロキシサーバを構築しHTTP headerを利用する

前提

環境

Node.js 15x
Nginx 1.19

結論

Dokcer-composeでNginxコンテナとWebアプリケーションを起動する。

詳細

$tree -L 2
.
├── Dockerfile
├── README.md
├── app
│   ├── Dockerfile
│   ├── node_modules
│   ├── package-lock.json
│   ├── package.json
│   └── server.js
├── docker-compose.yaml
└── nginx.conf

Docker-compose.yaml

services:
  nginx:
    image: nginx:alpine
    ports:
      - 80:80
    restart: always
    volumes: 
      - ./nginx.conf:/etc/nginx/nginx.conf

  web:
    depends_on:
      - nginx
    image: app
    restart: always
    container_name: web
    ports: 
      - 8080:8080

Dockerfile

FROM nginx:alpine

COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80

nginx.conf

events {}
http {
  server { 
    listen 80;
    server_name localhost;
    location / {
      proxy_pass      http://web:8080;
      proxy_set_header  X-Forwarded-Host    $host;
    }
  }
}

app

app/Dockerfile

FROM node

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 8080
CMD [ "npm", "start" ]

app/package.json

{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "First Last <first.last@example.com>",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.16.1"
  }
}

app/server.js

'use strict';

const express = require('express');

const PORT = 8080;
const HOST = '0.0.0.0';

const app = express();
app.get('/', (req, res) => {
  res.json(req.headers)
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

動作確認

$docker-compose up -d
$curl localhost
{"x-forwarded-host":"localhost","host":"web:8080","connection":"close","user-agent":"curl/7.54.0","accept":"*/*"}

HTTPヘッダが渡ってくることが確認できた。