4
votes

I set up a MongoDB instance on Google cloud using the click-to-deploy feature. I have been trying to connect to the server from another Ubuntu GCP instance using the command line. However, I can't seem to.

I have added a firewall rule to allow my MongoDB instance to listen on port 27017. I used the instruction

 gcloud compute firewall-rules create default-allow-mongo \
     --allow tcp:27017 \
     --source-ranges 0.0.0.0/0 \
     --target-tags mongodb \
     --description "Allow mongodb access to all IPs"

As instructed in Google Cloud Mongo DB external ip not connecting I checked using

 netstat -an | grep -i listen | grep tcp 

I got the result


tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN 

I also changed the mongod.conf file on the MongoDB instance. I have added the internal IP of my GCP instance to the bindIP.

This is the code I was using to connect to the MongoDB client:

client =  MongoClient('mongodb://username:[email protected]:27017')
# X.X.X.X = external IP of mongoDB instance

mydb = client['test2']  
posts = mydb.posts
data = {}
data['id'] = 1
posts.insert(data)

I keep getting this error:

pymongo.errors.ServerSelectionTimeoutError: X.X.X.X:27017: timed out 

I would really appreciate it if somebody could help me out.

Thanks

1

1 Answers

4
votes

The issue has been resolved.

There are three things I did :

(1) Add the MongoDB instance tag to the GCP instance tag using:

    gcloud compute instances add-tags example-instance --tags tag-1,tag-2

(2) I had allocated very little space to the MongoDB instance. I increased it from 10 GB to 100 GB.

(3) In the mongo.conf file, change the bindIP and include the internal IP of the MongoDB instance, and NOT the internal IP of the GCP instance you're trying to access from.

This is an excellent reference : http://www.mkyong.com/mongodb/mongodb-allow-remote-access/