title: Accessing MongoDB instance on Google Cloud
body: <p>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. </p>
  
  <p>I have added a firewall rule to allow my MongoDB instance to listen on port 27017. I used the instruction </p>
  
  <pre>
   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"
  </pre>
  
  <p>As instructed in <a href="https://stackoverflow.com/questions/29135528/google-cloud-mongo-db-external-ip-not-connecting?lq=1">Google Cloud Mongo DB external ip not connecting</a> I checked using <pre> netstat -an | grep -i listen | grep tcp </pre></p>
  
  <p>I got the result</p>
  
  <pre>
  
  tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN 
  </pre>
  
  <p>I also changed the mongod.conf file on the MongoDB instance. I have added the internal IP of my GCP instance to the bindIP.</p>
  
  <p>This is the code I was using to connect to the MongoDB client:</p>
  
  <pre><code>client =  MongoClient('mongodb://username:password@X.X.X.X:27017')
  # X.X.X.X = external IP of mongoDB instance
  
  mydb = client['test2']  
  posts = mydb.posts
  data = {}
  data['id'] = 1
  posts.insert(data)
  </code></pre>
  
  <p>I keep getting this error:</p>
  
  <pre><code>pymongo.errors.ServerSelectionTimeoutError: X.X.X.X:27017: timed out 
  </code></pre>
  
  <p>I would really appreciate it if somebody could help me out.</p>
  
  <p>Thanks</p>