如何在 Nginx 反向代理后面设置 MongoDB

2023-12-20

我正在尝试将 Nginx 设置为访问 MongoDB 数据库的反向代理。默认情况下,Mongo 监听 27017 端口。我想要做的是通过 nginx 重定向主机名(例如 mongodb.mysite.com)并将其传递到 mongodb 服务器。通过这种方式,从外部网络我将关闭已知的 27017 端口,并从隐藏的 url 访问我的数据库,就像我给出的示例一样。

所以我尝试使用以下配置设置 Nginx:

server {
        listen 80;
        server_name mongo.mysite.com;
        gzip off;       

        location / {
            proxy_pass http://127.0.0.1:27017;
            proxy_redirect off;
            proxy_buffering off;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }

因此,在完成此操作后,我尝试使用以下命令从 cmd 与 mongo shell 连接mongo mongo.mysite.com:80我得到以下错误:

2015-08-06T13:44:32.670+0300 I NETWORK  recv(): message len 1347703880 is invalid. Min 16 Max: 48000000
2015-08-06T13:44:32.670+0300 I NETWORK  DBClientCursor::init call() failed
2015-08-06T13:44:32.674+0300 E QUERY    Error: DBClientBase::findN: transport error: mongo.therminate.com:80 ns: admin.$cmd query: { whatsmyuri: 1 }
    at connect (src/mongo/shell/mongo.js:181:14)
    at (connect):1:6 at src/mongo/shell/mongo.js:181
exception: connect failed

另外,在 Nginx 访问日志中我得到以下信息:

94.66.184.128 - - [06/Aug/2015:10:44:32 +0000] "<\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xD4\x07\x00\x00\x00\x00\x00\x00admin.$cmd\x00\x00\x00\x00\x00\x01\x00\x00\x00\x15\x00\x00\x00\x10whatsmyuri\x00\x01\x00\x00\x00\x00" 400 172 "-" "-"

有谁知道这里出了什么问题吗?谢谢!


你是对的,你需要通过在 .conf 文件中添加一个流部分来使用 NGINX 的流模块:

stream {
    server {
        listen  <your incoming Mongo TCP port>;
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass    stream_mongo_backend;
    }

    upstream stream_mongo_backend {
      server <localhost:your local Mongo TCP port>;
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Nginx 反向代理后面设置 MongoDB 的相关文章

随机推荐