mit*_*1os 16 url proxy redirect nginx mongodb
大家好我想设置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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以在这之后我尝试使用命令从我的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
Run Code Online (Sandbox Code Playgroud)
同样在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 "-" "-"
Run Code Online (Sandbox Code Playgroud)
有没有人有想法,这里出了什么问题?谢谢!
mit*_*1os 18
我把它留在了后面,但经过一些工作后,我不得不再次面对这个问题,这次解决方案突然出现了!
NGINX基本上是一个HTTP服务器,因此通过以上方式设置重定向和代理,它包装了HTTP协议中的所有通信.所以正在发生的错误是,当Mongo期待Raw TCP流量时,它正在获得HTTP流量.
因此,解决方案是使用NGINX的新功能stream module,用于处理原始TCP流量并设置上游服务器指向mongodb实例.
更多信息:NGINX流模块
Nés*_*tor 15
你是对的,你需要通过在你的.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>;
}
}
Run Code Online (Sandbox Code Playgroud)
Kin*_*ame 12
除了@Néstor的回答.
这个配置应该写入/etc/nginx.conf上面的http部分,如下所示:
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>;
}
}
http {
...
}
Run Code Online (Sandbox Code Playgroud)
你永远不应该把它写入.conf文件并将文件放入/etc/nginx/sites-available文件夹.因为/etc/nginx/sites-available文件夹中的任何配置信息都属于该http部分