arrow_back

Running a MongoDB Database in Kubernetes with StatefulSets

Join Sign in
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

Running a MongoDB Database in Kubernetes with StatefulSets

Lab 1 hour universal_currency_alt 5 Credits show_chart Intermediate
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

This lab was developed with our partner, MongoDB. Your personal information may be shared with MongoDB, the lab sponsor, if you have opted-in to receive product updates, announcements, and offers in your Account Profile.

GSP022

Google Cloud self-paced labs logo

Overview

Kubernetes is an open source container orchestration tool that handles the complexities of running containerized applications. You can run Kubernetes applications with Kubernetes Engine—a Google Cloud computing service that offers many different customizations and integrations. In this lab, you will get some practical experience with Kubernetes by learning how to set up a MongoDB database with a StatefulSet. Running a stateful application (a database) on a stateless service (container) may sound contradictory. However, after getting hands-on practice with this lab you will quickly see how that's not the case. In fact, by using a few open-source tools you will see how Kubernetes and stateless services can go hand-in-hand.

What you'll learn

In this lab, you will learn the following:

  • How to deploy a Kubernetes cluster, a headless service, and a StatefulSet.
  • How to connect a Kubernetes cluster to a MongoDB replica set.
  • How to scale MongoDB replica set instances up and down.
  • How to clean up your environment and shutdown the above services.

Prerequisites

This is an advanced level lab. Familiarity with Kubernetes or containerized applications is suggested. Experience with the Google Cloud Shell/SDK and MongoDB is also recommended. If you are looking to get up to speed in these services, be sure to check out the following labs:

Once you're ready, scroll down to get your lab environment set up.

Setup

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Set a compute zone

Throughout this lab, we will be using the gcloud command line tool to provision our services.

  • Before we can create our Kubernetes cluster, we will need to set a compute zone so that the virtual machines in our cluster are all created in the same region. We can do this using the gcloud config set command—run the following in your cloud shell to set your zone to :
gcloud config set compute/zone {{{project_0.default_zone | ZONE}}} Note: Learn more about regions and zones from the Regions and zones guide.

Task 2. Create a new cluster

Now that our zone is set, we will create a new cluster of containers.

  • Run the following command to instantiate a cluster named hello-world:
gcloud container clusters create hello-world --num-nodes=2

This command creates a new cluster with two nodes, or virtual machines. You can configure this command with additional flags to change the number of nodes, the default permissions, and other variables. Learn more from the gcloud container clusters create reference.

Launching the cluster may take a few minutes. Once it's up, you should receive a similar output:

NAME Location MATER_VERSION MASTER_IP ... hello-world {{{project_0.default_zone | ZONE}}} 1.9.7-gke.3 35.184.131.251 ...

Click Check my progress to verify the objective.

Create a new Cluster

Task 3. Setting up

Now that we have our cluster up and running, it's time to integrate it with MongoDB. We will be using a replica set so that our data is highly available and redundant—a must for running production applications.

To get set up, we need to do the following:

  1. Run the following command to clone the MongoDB/Kubernetes replica set from the Github repository:
gsutil -m cp -r gs://spls/gsp022/mongo-k8s-sidecar .
  1. Once it's cloned, navigate to the StatefulSet directory with the following command:
cd ./mongo-k8s-sidecar/example/StatefulSet/

Once you have verified that the files have been downloaded and that you're in the right directory, let's go ahead and create a Kubernetes StorageClass.

Create the StorageClass

A StorageClass tells Kubernetes what kind of storage you want to use for database nodes. On the Google Cloud, you have a couple of storage choices: SSDs and hard disks.

If you take a look inside the StatefulSet directory (you can do this by running the ls command), you will see SSD and HDD configuration files for both Azure and Google Cloud.

  1. Run the following command to take a look at the googlecloud_ssd.yaml file:
cat googlecloud_ssd.yaml

Output:

kind: StorageClass apiVersion: storage.k8s.io/v1beta1 metadata: name: fast provisioner: kubernetes.io/gce-pd parameters: type: pd-ssd

This configuration creates a new StorageClass called "fast" that is backed by SSD volumes.

  1. Run the following command to deploy the StorageClass:
kubectl apply -f googlecloud_ssd.yaml

Now that our StorageClass is configured, our StatefulSet can now request a volume that will automatically be created.

Click Check my progress to verify the objective.

Create the StorageClass

Task 4. Deploying the Headless Service and StatefulSet

Find and inspect the files

  1. Before we dive into what headless service and StatefulSets are, let's open up the configuration file (mongo-statefulset.yaml) where they are both housed in:
nano mongo-statefulset.yaml

You should receive the following output (without the pointers to the Headless Service and StatefulSet content):

apiVersion: v1 <----------- Headless Service configuration kind: Service metadata: name: mongo labels: name: mongo spec: ports: - port: 27017 targetPort: 27017 clusterIP: None selector: role: mongo --- apiVersion: apps/v1 <------- StatefulSet configuration kind: StatefulSet metadata: name: mongo spec: serviceName: "mongo" replicas: 3 selector: matchLabels: role: mongo template: metadata: labels: role: mongo environment: test spec: terminationGracePeriodSeconds: 10 containers: - name: mongo image: mongo command: - mongod - "--replSet" - rs0 - "--smallfiles" - "--noprealloc" ports: - containerPort: 27017 volumeMounts: - name: mongo-persistent-storage mountPath: /data/db - name: mongo-sidecar image: cvallance/mongo-k8s-sidecar env: - name: MONGO_SIDECAR_POD_LABELS value: "role=mongo,environment=test" volumeClaimTemplates: - metadata: name: mongo-persistent-storage annotations: volume.beta.kubernetes.io/storage-class: "fast" spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 50Gi
  1. Remove the following flags from the file (lines 49 and 50):
- "--smallfiles" - "--noprealloc"
  1. Ensure that this section of your file looks like the following:
containers: - name: mongo image: mongo command: - mongod - "--replSet" - rs0 ports: - containerPort: 27017 volumeMounts: - name: mongo-persistent-storage mountPath: /data/db
  1. Exit the nano editor with CTRL+X > Y > ENTER.

Headless service: overview

The first section of mongo-statefulset.yaml refers to a headless service. In Kubernetes terms, a service describes policies or rules for accessing specific pods. In brief, a headless service is one that doesn't prescribe load balancing. When combined with StatefulSets, this will give us individual DNSs to access our pods, and in turn a way to connect to all of our MongoDB nodes individually. In the yaml file, you can make sure that the service is headless by verifying that the clusterIP field is set to None.

StatefulSet: overview

The StatefulSet configuration is the second section of mongo-statefulset.yaml. This is the bread and butter of the application: it's the workload that runs MongoDB and what orchestrates your Kubernetes resources. Referencing the yaml file, we see that the first section describes the StatefulSet object. Then, we move into the Metadata section, where labels and the number of replicas are specified.

Next comes the pod spec. The terminationGracePeriodSeconds is used to gracefully shutdown the pod when you scale down the number of replicas. Then the configurations for the two containers are shown. The first one runs MongoDB with command line flags that configure the replica set name. It also mounts the persistent storage volume to /data/db: the location where MongoDB saves its data. The second container runs the sidecar. This sidecar container will configure the MongoDB replica set automatically. As mentioned earlier, a "sidecar" is a helper container that helps the main container run its jobs and tasks.

Finally, there is the volumeClaimTemplates. This is what talks to the StorageClass we created before to provision the volume. It provisions a 100 GB disk for each MongoDB replica.

Deploy Headless Service and the StatefulSet

Now that we have a basic understanding of what a headless service and StatefulSet are, let's go ahead and deploy them.

  • Since the two are packaged in mongo-statefulset.yaml, we can run the following command to run both of them:
kubectl apply -f mongo-statefulset.yaml

You should receive the following output:

service/mongo created statefulset.apps/mongo created

Click Check my progress to verify the objective.

Deploying the Headless Service and StatefulSet

Task 5. Connect to the MongoDB Replica set

Now that we have a cluster running and our replica set deployed, let's go ahead and connect to it.

Wait for the MongoDB replica set to be fully deployed

Kubernetes StatefulSets deploys each pod sequentially. It waits for the MongoDB replica set member to fully boot up and create the backing disk before starting the next member.

  • Run the following command to view and confirm that all three members are up:
kubectl get statefulset

Output - all three members are up:

NAME READY AGE mongo 3/3 103s

Initiating and Viewing the MongoDB replica set

At this point, you should have three pods created in your cluster. These correspond to the three nodes in your MongoDB replica set.

  1. Run this command to view:
kubectl get pods

Output:

NAME READY STATUS RESTARTS AGE mongo-0 2/2 Running 0 3m mongo-1 2/2 Running 0 3m mongo-2 2/2 Running 0 3m
  1. Wait for all three members to be created before moving on.

  2. Connect to the first replica set member:

kubectl exec -ti mongo-0 -- mongosh

You now have a REPL environment connected to the MongoDB.

  1. Let's instantiate the replica set with a default configuration by running the rs.initiate() command:
rs.initiate()
  1. Print the replica set configuration; run the rs.conf() command:
rs.conf()

This outputs the details for the current member of replica set rs0. In this lab you see only one member. To get details of all members you need to expose the replica set through additional services like nodeport or load balancer.

rs0:OTHER> rs.conf() { "_id" : "rs0", "version" : 1, "protocolVersion" : NumberLong(1), "writeConcernMajorityJournalDefault" : true, "members" : [ { "_id" : 0, "host" : "localhost:27017", "arbiterOnly" : false, "buildIndexes" : true, "hidden" : false, "priority" : 1, "tags" : { }, "slaveDelay" : NumberLong(0), "votes" : 1 } ], "settings" : { "chainingAllowed" : true, "heartbeatIntervalMillis" : 2000, "heartbeatTimeoutSecs" : 10, "electionTimeoutMillis" : 10000, "catchUpTimeoutMillis" : -1, "catchUpTakeoverDelayMillis" : 30000, "getLastErrorModes" : { }, "getLastErrorDefaults" : { "w" : 1, "wtimeout" : 0 }, "replicaSetId" : ObjectId("5c526b6501fa2d29fc65c48c") } }
  1. Type "exit" and press enter to quit the REPL.

Task 6. Scaling the MongoDB replica set

A big advantage of Kubernetes and StatefulSets is that you can scale the number of MongoDB Replicas up and down with a single command!

  1. To scale up the number of replica set members from 3 to 5, run this command:
kubectl scale --replicas=5 statefulset mongo

In a few minutes, there will be 5 MongoDB pods.

  1. Run this command to view them:
kubectl get pods

Your output should look like this:

NAME READY STATUS RESTARTS AGE mongo-0 2/2 Running 0 41m mongo-1 2/2 Running 0 39m mongo-2 2/2 Running 0 37m mongo-3 2/2 Running 0 4m mongo-4 2/2 Running 0 2m
  1. To scale down the number of replica set members from 5 back to 3, run this command:
kubectl scale --replicas=3 statefulset mongo

In a few seconds, there are 3 MongoDB pods.

  1. Run this command to view:
kubectl get pods

Your output should look like this:

NAME READY STATUS RESTARTS AGE mongo-0 2/2 Running 0 41m mongo-1 2/2 Running 0 39m mongo-2 2/2 Running 0 37m

Click Check my progress to verify the objective.

Scaling the MongoDB replica set

Task 7. Using the MongoDB replica set

Each pod in a StatefulSet backed by a Headless Service will have a stable DNS name. The template follows this format: <pod-name>.<service-name>

This means the DNS names for the MongoDB replica set are:

mongo-0.mongo mongo-1.mongo mongo-2.mongo

You can use these names directly in the connection string URI of your app.

Using a database is outside the scope of this lab, however for this case, the connection string URI would be:

"mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/dbname_?"

Task 8. Clean up

Because you are working in a lab environment, when you end the lab all your resources and your project will be cleaned up and discarded on your behalf. But we want to show you how to clean up resources yourself to save on cost and to be a good cloud citizen when you are in your own environment.

To clean up the deployed resources, run the following commands to delete the StatefulSet, Headless Service, and the provisioned volumes.

  1. Delete the StatefulSet:
kubectl delete statefulset mongo
  1. Delete the service:
kubectl delete svc mongo
  1. Delete the volumes:
kubectl delete pvc -l role=mongo
  1. Finally, you can delete the test cluster:
gcloud container clusters delete "hello-world"
  1. Press Y then Enter to continue deleting the test cluster.

Congratulations!

Kubernetes Engine provides a powerful and flexible way to run containers on Google Cloud. StatefulSets let you run stateful workloads like databases on Kubernetes. You learned about:

  • Creating a MongoDB replica set with Kubernetes StatefulSets
  • Connecting to the MongoDB replica set
  • Scaling the replica set

Finish your quest

This self-paced lab is part of the Cloud Architecture quest. A quest is a series of related labs that form a learning path. Completing a quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in any quest that contains this lab and get immediate completion credit. Refer to the Google Cloud Skills Boost catalog for all available quests.

Take your next lab

Continue your quest with the next lab, or check out these suggestions:

Next steps / learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated October 09, 2023

Lab Last Tested October 09, 2023

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.