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

时间:2015-08-06 10:46:49

标签: mongodb url redirect nginx proxy

大家好我正在尝试将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;
        }
    }

所以在这之后我尝试使用命令mongo mongo.mysite.com:80从我的cmd连接mongo shell并且我得到以下错误:

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 "-" "-"

有没有人有想法,这里出了什么问题?谢谢!

4 个答案:

答案 0 :(得分:16)

I left this behind, but after some work done, I had to face this problem again and the solution popped in my mind this time!

NGINX is basically an HTTP server, so by setting redirects and proxies the above way, it wraps all communication in HTTP protocol. So the error that is happening, is that while Mongo is expecting Raw TCP traffic, it is getting HTTP traffic.

So the solution to this is to use NGINX's new stream module that is used for handling raw TCP traffic and setup your upstream server to point to mongodb instance.

More Info : NGINX stream module

答案 1 :(得分:12)

你是对的,你需要通过在.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>;
  }
}

答案 2 :(得分:10)

@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 {
   ...
}

您应该从不将其写入.conf文件并将文件放入/etc/nginx/sites-available文件夹。因为/etc/nginx/sites-available文件夹中的任何配置信息都属于http部分

答案 3 :(得分:-1)

如果您通过通常的默认IP值连接到本地mongodb实例,它应该连接:mongo 10.8.8.10

问题在于通过未发生的mongodb shell解析地址。