Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using MongoDB with Google Cloud

Introduction

Google Cloud provides a robust and scalable platform for deploying MongoDB. You can use Google Compute Engine (GCE) or Google Kubernetes Engine (GKE) to run MongoDB. This tutorial will guide you through the steps to deploy and configure MongoDB on Google Cloud.

Setting Up

Before you begin, ensure that you have a Google Cloud account and have installed the Google Cloud SDK on your machine.

Creating a GCE Instance

To deploy MongoDB, you need to create a GCE instance. Follow these steps:

Creating GCE Instance

gcloud compute instances create my-instance \
  --zone=us-central1-a \
  --machine-type=e2-medium \
  --image-family=ubuntu-2004-lts \
  --image-project=ubuntu-os-cloud
            

Connecting to the GCE Instance

Connect to your GCE instance using SSH:

Connecting to GCE

gcloud compute ssh --zone "us-central1-a" "my-instance"
            

Installing MongoDB

Once connected, install MongoDB on the GCE instance:

Installing MongoDB

sudo apt update
sudo apt install -y mongodb
            

Start the MongoDB service:

Starting MongoDB

sudo systemctl start mongodb
            

Configuring MongoDB

Edit the MongoDB configuration file to bind MongoDB to the VM's public IP address:

Editing Configuration

sudo nano /etc/mongod.conf
# Change bindIp to 0.0.0.0 to allow remote connections
            

Restart the MongoDB service:

Restarting MongoDB

sudo systemctl restart mongodb
            

Securing MongoDB

For security, configure MongoDB authentication and set up firewall rules in Google Cloud:

Enabling Authentication

# Add the following lines to /etc/mongod.conf
security:
  authorization: enabled
            

Create an admin user in MongoDB:

Creating Admin User

use admin
db.createUser({
  user: "admin",
  pwd: "password",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
            

Setting Up Firewall Rules

Configure firewall rules in the Google Cloud Console to allow access to MongoDB from your IP address.

Conclusion

In this tutorial, you have learned how to deploy and configure MongoDB on Google Cloud. Using Google Cloud services provides a scalable and reliable platform for managing your MongoDB databases.