How to setup MongoDB behind Nginx Reverse Proxy

Adding onto @Néstor's answer, this config should be written to /etc/nginx/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.


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


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