Ben
Ben

Reputation: 244

Discovery of MongoDB Server IP from NodeJS Server

I have one instance of MongoDB running on a cloud compute on DigitalOcean. I have another instance of my Node(Express) app running on another cloud compute. Is there a way that I can discover the IP of the database such that I don't have to hard code it into my app and therefore can scale easier? I know you can hook the instances up to a load balancer and hardcode that in, but that isn't ideal and won't work in all circumstances, as it has to be reconfigured every time the environment changes. I would prefer not to have to make something that accesses the DigitalOcean API, as that is platform-specific, although I am considering it. The reason that I am asking is that I want to automate configuration as much as possible so that I don't have to a bunch of configuring every time I create/destroy instances. I am using static IPs, so changing IPs won't be a problem. I'm looking into service discovery systems such as consul, and I might move to something like that but I think it(consul) seems overkill for my app, although I am considering it.

Upvotes: 0

Views: 606

Answers (2)

dcstone09
dcstone09

Reputation: 41

You can use Environment Variables to avoid hardcoding values into your code. These values can be loaded from the processes environment when the application starts with a package like dotenv.

Upvotes: 4

Stennie
Stennie

Reputation: 65323

The normal means for discovering the current IP(s) of a web resource is using a DNS hostname. This doesn't require any additional services to be installed and will work with public or private IPs as long as the hostname is resolvable. There are low cost domain names available (few US$/year) which also include a service to alias domain hostnames (eg db.yourdomain.xyz) to your Digital Ocean hostname or IPs. Recommending a provider is outside the scope of Stack Overflow, but there are many. One aspect to compare is the renewal price, which is often much higher than the initial registration.

If you eventually upgrade your MongoDB deployment from a standalone to a replica set, MongoDB 3.6+ supports a DNS-based discovery format (SRV lookups) which allows you to change the hosts in a replica set without reconfiguring clients.

Load balancers and service discovery systems are overkill for managing a single server, but ultimately they expose resources via DNS as well. For example, see Consul's DNS interface (which also includes SRV lookups similar to MongoDB's DNS-based discovery format). You could also perform service discovery via HTTP requests to the Consul API, but that is a more complicated integration path.

Upvotes: 1

Related Questions