Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

url - How to setup MongoDB behind Nginx Reverse Proxy

I am trying to setup Nginx as a reverse proxy for accessing a MongoDB Database. By default Mongo listens to 27017 port. What I want to do, is redirect a hostname for example mongodb.mysite.com through nginx and pass it to mongodb server. In that way from the outside network I will have my known 27017 port closed, and access my db from a hidden url like the example I gave.

So I am trying to setup Nginx with this configuration :

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;
        }
    }

So after having this I try to connect with mongo shell from my cmd with the command mongo mongo.mysite.com:80 and I get back the following error:

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

Also in the Nginx access log I get this:

94.66.184.128 - - [06/Aug/2015:10:44:32 +0000] "<x00x00x00x00x00x00x00x00x00x00x00xD4x07x00x00x00x00x00x00admin.$cmdx00x00x00x00x00x01x00x00x00x15x00x00x00x10whatsmyurix00x01x00x00x00x00" 400 172 "-" "-"

Has anyone got an idea, what is going wrong here? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...