How to Connect to a MongoDB Server in a Private Network Using MongoDB Compass?
In this post, we’ll explore how to connect to a MongoDB server hosted within a private network.
MongoDB is a widely used NoSQL database. It’s generally recommended to host your MongoDB server (or any database) within a private subnet to minimize the risk of unauthorized access. This setup ensures that the database server is isolated from the public network, enhancing security. To access the database for development purposes, you would use a public-facing jump box (also known as a bastion host). Below is a basic architectural diagram illustrating this setup.
Connecting to MongoDB
Step 1:
Download and install MongoDB Compass from the MongoDB downloads page. Ensure you get the GUI version.
Step 2:
Open MongoDB Compass and click on “New Connection” on the left side. In the URI field, enter the connection string, which includes the username, password, and hostname of the MongoDB server. It should look something like this:
mongodb://username:password@host-name:27017/
The username and password are used for MongoDB user authentication. If your password contains special characters like $, #, or &, convert them to their UTF-8 equivalents (%24, %23, and %26, respectively).
Since MongoDB is hosted in a private subnet, the hostname should be a private IP address, such as 10.0.0.1 or 192.168.0.1.
Step 3:
Click on “Advanced Connection Options,” then go to the “Proxy/SSH” tab. If the bastion host requires a username and password, select “SSH with Password.” If it requires a .pem file for authentication, select “SSH with Identity File.”
Step 4:
Enter the SSH connection details:
- SSH Hostname: The public IP address or hostname of the SSH server (bastion host).
- SSH Port: 22 (default port for SSH).
- SSH Username: The username on the bastion host (e.g.,
root
orec2-user
for EC2 instances). Note that this is not the MongoDB server username. - SSH Identity File or SSH Passphrase: Depending on the authentication method, either enter the password for the user or upload the identity file (.pem). This is not the MongoDB server password.
Step 5:
Click the “Connect” button. It might take a few seconds, but if all steps are correctly followed, you should establish a secure connection to MongoDB.
Other Considerations:
Ensure that VPC peering is correctly configured if the bastion host and MongoDB are in different VPCs. Additionally, port 27017 must be open on the MongoDB server to allow connections from the bastion host. Depending on its configuration, the bastion host may need to whitelist your IP address and open SSH port 22.
Conclusion:
We covered the process of connecting to a MongoDB server within a private network using MongoDB Compass and a bastion host. If you have any questions or suggestions, please comment below or message me.