Google Compute Engine MongoDB error when connecting via Java driver

I created a new project and clicked to deploy a Compute MongoDB instance.

I have set up HTTP traffic for the primary VM instance.

Then in eclipse, I wrote the following code to determine if I can 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 VM list in the compute module.

I got 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 to open port 27017 on the default network in Google Compute and I was able to navigate to MongoDb.

Is this the right way to get the connection?

I have a fear that it will allow anyone to access the database and mess up the information stored inside. My guess is that I have to host my application in a virtual machine instance in the same network space on the compute engine and connect using an internal IP.

0


source to share


1 answer


While GCE instances have nearly unlimited access to the Internet (SMTP is a big exception) to allow incoming connections, an appropriate firewall rule must be configured on the network being used, as you well did. You can further customize the access rule by specifying the source IP address and port for these MongoDB connections, as well as use labels on VMs by specifying the same labels in the target part of the firewall rule, further restricting access only to the group of VMs that have this label. While an app hosted on Google Cloud Platform provides you with improved performance, it is by no means a prerequisite for using the framework.



In addition, you can always set up more secure means of connection such as VPN, etc.

0


source







All Articles