Sagar090
Sagar090

Reputation: 61

Not able to connect to mongodb server on google compute engine through my java code from my local machine

MongoClient mongo = new MongoClient("23.236.50.143",27017);
    System.out.print(mongo);
    List<String> dbs = mongo.getDatabaseNames();
    for(String db1 : dbs){
        System.out.println(db1);
}

23.236.50.143 is the external ip of the compute engine instance.

I have also added firewall rule to allow connection on port number 27017.

Still Connection Refused Error is coming.

What am I doing wrong??

Upvotes: 4

Views: 2330

Answers (1)

You have mentioned that you have added firewall rule to allow connection on port 27017. Make sure that you added this firewall rule in the Google Cloud Console dashboard or using gcloud command line utility.

After setting this, note the Internal IP of the compute engine instance, which is usually mentioned in the Google Cloud Console dahsboard.

Edit the Mongo config file (usually present at /etc/mongod.conf) to add the Internal IP of the compute engine instance in the bind_ip variable.

The config file will look like this:

$ vim /etc/mongod.conf
# /etc/mongod.conf

# Listen to local interface only. Comment out to listen on all interfaces.
bind_ip = 127.0.0.1

After adding your Internal IP, the config file will look like this:

$ vim /etc/mongod.conf

# /etc/mongod.conf

# Listen to local and LAN interfaces.
bind_ip = 127.0.0.1,X.X.X.X

where X.X.X.X is the Internal IP of your instance. Save the file and restart mongo server.

Note: Don't use the External IP in the mongo config file.

Reference: MKyong.com : MongoDB – Allow remote access

Upvotes: 3

Related Questions