Run MongoDB on Google Cloud Platform

MongoDB is an open source (AGPL licensed), NoSQL document database.

It's easy to get started developing MongoDB apps running on Google Cloud Platform. And because the apps you create will be running on the same infrastructure that powers all of Google's products, you can be confident that they will scale to serve all of your users, whether there are a few or millions of them.

This tutorial gets you going fast by deploying a simple MongoDB app. This tutorial assumes that you are familiar with Node.js programming and that you have already Prepared Your Environment for Node.js Development.

Before you begin

Check off each step as you complete it.

  1. check_box_outline_blank check_box Create a project in the Google Cloud Platform Console.
    If you haven't already created a project, create one now. Projects enable you to manage all Google Cloud Platform resources for your app, including deployment, access control, billing, and services.
    1. Open the Cloud Platform Console.
    2. In the drop-down menu at the top, select Create a project.
    3. Click Show advanced options. Under App Engine location, select a United States location.
    4. Give your project a name.
    5. Make a note of the project ID, which might be different from the project name. The project ID is used in commands and in configurations.
  2. check_box_outline_blank check_box Enable billing for your project, and sign up for a free trial.

    If you haven't already enabled billing for your project, enable billing now, and sign up for a free trial. Enabling billing allows the application to consume billable resources such as running instances and storing data. During your free trial period, you won't be billed for any services.

  3. check_box_outline_blank check_box Install the Google Cloud SDK.

    If you haven't already installed the Google Cloud SDK, install and initialize the Google Cloud SDK now. The SDK contains tools and libraries that enable you to create and manage resources on Google Cloud Platform.

Download and run the app

After you've completed the prerequisites, you can download and deploy the MongoDB sample app. The following sections guide you through getting the MongoDB app up and running.

Clone the MongoDB app

The code for the MongoDB sample app is in the GoogleCloudPlatform/nodejs-docs-samples repository on GitHub. If you haven't already, copy the repository to your local machine:

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

Go to the directory that contains the sample code:

cd nodejs-docs-samples
The MongoDB sample app is in the appengine folder:

cd appengine/mongodb

Alternatively, you can download the sample as a zip and extract it.

Create a MongoDB database

There are multiple options for creating a new MongoDB database. For example:

  • Create a Google Compute Engine virtual machine with MongoDB pre-installed.
  • Use mLab to create a free MongoDB deployment on Google Cloud Platform.

Create a JSON file that describes your database

In the mongodb folder, create a file named keys.json that contains contains the information required to connect to your MongoDB database. Here's an example:

{
  "mongoHost": "ds053894.mlab.com",
  "mongoPort": "53894",
  "mongoDatabase": "mydata",
  "mongoUser": "myapp",
  "mongoPass": "mypword"
}

Note that keys.json has been added to the .gitignore file, so that your credentials don't get checked in to source control.

Run the app on your local computer

  1. Install dependencies:

    npm install
    
  2. Run the start script:

    npm start
    
  3. In your web browser, enter this address:

    http://localhost:8080
    

You can see the sample app displayed in the page. This page is delivered by the MongoDB web server running on your computer.

When you're ready to move forward, press Ctrl+C to stop the local web server.

MongoDB code review

The server.js file contains the JavaScript code to start a server and respond to requests. Each time a client sends a request to the server, the app adds the IP address of the client to a collection in your MongoDB database. The server responds by returning a list of all IP addresses that have visited the site.

The following code creates a MongoDB client and connects it to a MongoDB server.

let uri = `mongodb://${user}:${pass}@${host}:${port}`;
if (nconf.get('mongoDatabase')) {
  uri = `${uri}/${nconf.get('mongoDatabase')}`;
}
console.log(uri);

mongodb.MongoClient.connect(uri, (err, db) => {
  if (err) {
    throw err;
  }

  // Create a simple little server.
  http.createServer((req, res) => {
    if (req.url === '/_ah/health') {
      res.writeHead(200, {
        'Content-Type': 'text/plain'
      });
      res.write('OK');
      res.end();
      return;
    }
    // Track every IP that has visited this site
    const collection = db.collection('IPs');

    const ip = {
      address: req.connection.remoteAddress
    };

    collection.insert(ip, (err) => {
      if (err) {
        throw err;
      }

      // push out a range
      let iplist = '';
      collection.find().toArray((err, data) => {
        if (err) {
          throw err;
        }
        data.forEach((ip) => {
          iplist += `${ip.address}; `;
        });

        res.writeHead(200, {
          'Content-Type': 'text/plain'
        });
        res.write('IPs:\n');
        res.end(iplist);
      });
    });
  }).listen(process.env.PORT || 8080, () => {
    console.log('started web process');
  });
});

Deploy the app to Google Cloud Platform

Enter this command to deploy the sample:

gcloud app deploy

Wait for the message that notifies you that the app update has completed.

See the app run in the cloud

In your web browser, enter this address:

https://<your-project-id>.appspot.com

This time, the page is delivered by a web server running in the App Engine flexible environment.

If you update your app, you can deploy the updated version by entering the same command you used to deploy the app the first time. The new deployment creates a new version of your app and promotes it to the default version. The older versions of your app remain, as do their associated VM instances. Be aware that all of these app versions and VM instances are billable resources. For information about deleting or stopping your VM instances, see Cleaning up.

For convenience, you can use an npm script to run the gcloud command. Add these lines to your package.json file:

"scripts": {
  "start": "node ./server.js",
  "deploy": "gcloud app deploy  --project <your-project-id>"
}

Now you can run this command to deploy your application:

npm run deploy

Configuration

Every app that runs in the App Engine flexible environment requires an app.yaml file to describe its deployment configuration.

runtime: nodejs
env: flex

This minimal app.yaml file sets the runtime to nodejs with the flexible environment. There are many other configuration values you can specify in app.yaml that allow you to customize resources, scaling, and other settings. For details about the configuration settings for the flexible environment, see App Engine flexible environment.

Bookshelf app logo

MongoDB documentation

MongoDB has documentation to help you get started.

Cleaning up

If you're done with the tutorials and want to clean up resources that you've allocated, see Cleaning Up.

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...