Reputation: 3
I created a new project and Click to Deploy a MongoDB Compute instance.
I set the primary VM instance to allow HTTP traffic.
Then in eclipse I wrote the following code to determine if I could connect to the MongoDB instance.
MongoClient mongoClient = new MongoClient(EXTERNAL_IP);
List<String> dbs = mongoClient.getDatabaseNames();
for(String db : dbs){
System.out.println(db);
}
The EXTERNAL_IP constant is the IP address copied from the list of VM in Compute Engine.
I was getting the following exception:
Exception in thread "AWT-EventQueue-0" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=EXTERNAL_IP:27017, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
Then I tried opening port 27017 in the default network on Google Compute and I was able to get through to MongoDb.
Is this the correct thing to do to get a connection?
I have a fear that it would allow anyone to gain access to the database and mess with the information stored within. I assume that I am meant to place my app in a VM Instance in the same network space on compute engine and connect using the Internal IP.
Upvotes: 0
Views: 746
Reputation: 1076
While GCE instances have almost unrestricted access to the internet (SMTP being the big exception), in order to allow incoming connections, the appropriate firewall rule needs to be set up on the network being used, as you well did. You can further fine-tune the access rule by specifying source IP and port for these MongoDB connections, as well as use labels on the VMs, specifying these same labels in the destination part of the firewall rule, further limiting access to only the group of VMs that have that label. And while having you app hosted on the Google Cloud Platform grants you improved performance, it is by no means a prerequisite to use the environment.
Additionally, you can always set up more secure means of connection, such as VPNs, et al.
Upvotes: 0