node.js - Express、Docker 和 Nginx - Express 中未显示真实 IP
问题描述
我有一个 dockerized 的 api 网关,并使用 nginx 作为负载均衡器。我需要获取原始客户端的 ip 地址,但它不起作用,我一直在获取 nginx ip(我知道这是 nginx ip,因为如果我向它发出请求,我会从我的应用程序中得到响应)
nginx.conf
# cache requests for 10m up to 10g with auto removal after 60m
proxy_cache_path /tmp/nginx_cache/ levels=1:2 keys_zone=backcache:10m max_size=10g
inactive=60m use_temp_path=off;
# allow 10 requests per second with burst cap at 20 (see location block)
limit_req_zone $binary_remote_addr zone=custom_limit:10m rate=10r/s;
upstream gateway {
# balance requests based on which gateway has the least # of active connections
server gateway_a:4001;
server gateway_b:4002;
}
server {
listen 80;
gzip on;
location / {
# rate-limit but allow for bursting of up to 20 req with nodelay in queue additions
limit_req zone=custom_limit burst=20 nodelay;
proxy_http_version 1.1;
# cache config
proxy_cache backcache;
proxy_cache_bypass $http_upgrade;
proxy_cache_revalidate on;
proxy_cache_min_uses 3;
proxy_cache_use_stale error timeout updating http_500 http_502
http_503 http_504;
proxy_cache_background_update on;
proxy_cache_lock on;
# proxy headers
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Remote-Port $remote_port;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://gateway;
}
}
index.js
import os from "os";
import express from "express";
import setupLogging from "./logging";
import setupProxies from "./proxy";
import ROUTES from "./routes";
const { PORT = 8080 } = process.env;
const app = express();
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
}),
);
setupLogging(app);
setupProxies(app, ROUTES);
app.set("trust proxy", true);
app.get("/", (req, res) =>
res.send(`<h1>Hi, my name is ${os.hostname()}</h1>`)
);
app.get("/health", (req, res) => res.sendStatus(200));
app.listen(PORT, () => {
global.console.info(`Gateway listening at http://localhost:${PORT}`);
});
我也在使用 http-proxy-middleware 库,我需要处理 onProxyReq 选项上的 ip 地址
解决方案
推荐阅读
- ios - 带有端口映射的 docker-compose 中的 iOS postgres
- elasticsearch - 在 Kibana 中升级 Xpack 许可证
- shellexecute - 使用 Shellexecute 在后台静默打开应用程序
- java - 需要一些关于 requireNonNull 的说明
- react-native - 即使 props 有索引,也无法访问 props.index
- javascript - 如何删除位于圆圈边界之外的标记?
- tfs - TFS 无法识别导入的数据库
- spring - 在 Twitter 克隆应用程序中关注用户的 Spring Rest Api 设计?
- typescript - 为什么 TypeScript 有一个结构化的类型系统?
- java - 如何在 e clipse 中配置生成的 Sources