Can you proxy MongoDB connection with Nginx? Sure you can!

Nginx is a powerful webserver and it serves well as proxy server too. I wanted to show you how easily you can setup a configuration that proxies MongoDB connection.

A few days ago we encountered a problem: How to connect to MongoDB from another machine if it is binded only to local network interface? At first we wanted to change the configuration of the database and restart it, but the problem was with the downtime. During a working day, the database should be available 100% and we couldn't wait until the next day to do the restart. Then we've came up with an idea of a proxy. We can sure setup a TCP proxy server that binds to network interface on a port and proxies a connection to local interface where MongoDB was binded. We use extensively Golang language and wanted to give a shot for custom app. But then we realised that we have Nginx server installed on the machine where database resides and another question came up: Can you proxy connection to MongoDB with Nginx?. After some trial and error we succeeded and avoided a need to write a single line of code.

Let's get straight to the point. Open and edit your /etc/nginx/nginx.conf file and add this snippet above http{ } directive.

stream {
    server {
        listen  27020 so_keepalive=on;
        proxy_connect_timeout 2s;
        proxy_pass    stream_mongo_backend;
        proxy_timeout 10m;
    }

    upstream stream_mongo_backend {
         server 127.0.0.1:27017;
    }

}

Let's break it into pieces

server {
    listen  27020 so_keepalive=on;
    proxy_connect_timeout 2s;
    proxy_pass    stream_mongo_backend;
    proxy_timeout 10m;
}

Open up a socekt on 27020 port that will accept connections with given timeouts. The so_keepalive=on is required for the connection to become a longlived and not setup a new connection to the backend server

upstream stream_mongo_backend {
     server 127.0.0.1:27017;
}

The upstream deirective instructs Nginx what is the target destiantion of the proxied stream.

Attention

Binding MongoDB only to local interface is dictated by the need to restrict access from the outside. Be aware that setting up a proxy for remote connections you can expose a database that has no authorization required. Be sure that you have authorization enabled or setup proper firewall rules that will filter traffic coming to MongoDB or proxy server.



Similar searches: proxy mongodb nginx / nginx mongodb tcp proxy / nginx tcp proxy / nginx stream proxy

These posts might be interesting for you:

  1. 3-węzłowy zestaw repliki MongoDB z SystemD i metrykami w Telegraf / Grafana
  2. Klaster RabbitMQ na Dockerze z Nodejs w 5 minut
  3. Handling Promise rejections in Express.js (Node.js) with ease
Author: Peter

I'm a backend programmer for over 10 years now, have hands on experience with Golang and Node.js as well as other technologies, DevOps and Architecture. I share my thoughts and knowledge on this blog.