How to setup MongoDB behind Nginx Reverse Proxy

前端 未结 4 552
醉酒成梦
醉酒成梦 2020-12-15 19:39

Hi guys 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

相关标签:
4条回答
  • 2020-12-15 19:46

    If you connect to your local instance of mongodb via the usual default ip values it should connect:mongo 10.8.8.10

    The issue is with resolving the address via the mongodb shell which is not happening.

    0 讨论(0)
  • 2020-12-15 19:50

    You're right, you need to use NGINX's stream module by adding a stream section to your .conf file:

    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>;
      }
    }
    
    0 讨论(0)
  • 2020-12-15 20:03

    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

    0 讨论(0)
  • 2020-12-15 20:11

    Adding onto @Néstor's answer, this config should be written to /etc/nginx.conf just above http section, like this:

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

    You should NEVER write it into a .conf file and put the file into /etc/nginx/sites-available folder. Because any config info in the /etc/nginx/sites-available folder belong to the http section.

    0 讨论(0)
提交回复
热议问题