Powered By GitBook
nodejs-redis-on-appengine
Learn how to connect to Redis from a Node.js app running in the App Engine flexible environment.
Contributed by Google employees.
You can check out Node.js and Google Cloud to get an overview of Node.js itself and learn ways to run Node.js apps on Google Cloud.

Prerequisites

    1.
    Create a project in the Cloud Console.
    2.
    Enable billing for your project.
    3.
    Install the Cloud SDK.

Start a Redis server

There are multiple options for creating a new Redis server:
    ​Host a Redis instance on
    Compute Engine.
    Use Redis Labs to
    create a free Redis-as-a-Service account.

Using Compute Engine

To use a hosted Redis instance on Compute Engine:
    1.
    Launch a Compute Engine virtual machine with
    by Bitnami.
    2.
    After the virtual machine launches,
    Set the IP address region to the location of your Redis virtual machine
    instance. Then, select the instance in the Attached To dropdown, and
    click Reserve. This IP address is your Redis hostname.
    3.
    Under your Redis virtual machine instance in
    ​Compute Engine, find
    your Bitnami Base Password under Custom Metadata. Use this as your
    Redis key.
    4.
    By default, your Redis port number is 6379. You can verify this by using
    SSH to connect to your Redis virtual machine instance and then typing
    redis-cli.
    5.
    After you have completed these steps, create a configuration file and connect to your hosted Redis instance. For example:
    1
    {
    2
    "redisHost": "1.2.3.4",
    3
    "redisPort": 6379,
    4
    "redisKey": "bitnami_base_password"
    5
    }
    Copied!

Using Redis Labs

To create a new Redis instance using Redis Labs:
    1.
    Create a new Redis subscription.
    2.
    Choose the cloud GCE/us-central1.
    3.
    Choose the free tier.
    4.
    Click select.
    5.
    Enter a resource name and password.
    6.
    Go to My Resources β†’ Manage and click on your Redis instance. You should see a URL that looks similar to the one below.
    1
    pub-redis-12345.us-central1-2-3.gce.garantiadata.com:12345
    Copied!
    Your Redis hostname consists of everything before the colon, and your Redis port number is the number after the colon. Use your Redis table password as the key value. For example, if your Redis table had a password of password, the URL above would be configured as follows:
    1
    {
    2
    "redisHost": "pub-redis-12345.us-central1-2-3.gce.garantiadata.com",
    3
    "redisPort": 12345,
    4
    "redisKey": "password"
    5
    }
    Copied!
    7.
    Using this information, create a configuration file and connect to your Redis Labs instance.

Connecting to a Redis server

Create a configuration file

Create a JSON file named keys.json that contains your Redis host name, port, and password. Do not check your credentials into source control. Create a .gitignore file if you don't have one, and add keys.json to it.
1
{
2
"redisHost": [YOUR_REDIS_HOSTNAME],
3
"redisPort": [YOUR_REDIS_PORT_NUMBER],
4
"redisKey": [YOUR_REDIS_PASSWORD]
5
}
Copied!
Replace [YOUR_REDIS_HOSTNAME], [YOUR_REDIS_PORT_NUMBER], and [YOUR_REDIS_PASSWORD] with your Redis hostname, port number, and password respectively.

Prepare the application

    1.
    Initialize a package.json file with the following command:
    1
    npm init
    Copied!
    2.
    Install dependencies:
    1
    npm install --save redis nconf
    Copied!
    3.
    Create a server.js file with the following contents:
    1
    'use strict';
    2
    ​
    3
    const redis = require('redis');
    4
    const http = require('http');
    5
    const nconf = require('nconf');
    6
    ​
    7
    // Read in keys and secrets. Using nconf use can set secrets via
    8
    // environment variables, command-line arguments, or a keys.json file.
    9
    nconf.argv().env().file('keys.json');
    10
    ​
    11
    // Connect to a redis server provisioned over at
    12
    // Redis Labs. See the README for more info.
    13
    const client = redis.createClient(
    14
    nconf.get('redisPort') || '6379',
    15
    nconf.get('redisHost') || '127.0.0.1',
    16
    {
    17
    'auth_pass': nconf.get('redisKey'),
    18
    'return_buffers': true
    19
    }
    20
    ).on('error', (err) => console.error('ERR:REDIS:', err));
    21
    ​
    22
    // Create a simple little server.
    23
    http.createServer((req, res) => {
    24
    client.on('error', (err) => console.log('Error', err));
    25
    ​
    26
    // Track every IP that has visited this site
    27
    const listName = 'IPs';
    28
    client.lpush(listName, req.connection.remoteAddress);
    29
    client.ltrim(listName, 0, 25);
    30
    ​
    31
    // push out a range
    32
    let iplist = '';
    33
    client.lrange(listName, 0, -1, (err, data) => {
    34
    if (err) {
    35
    console.log(err);
    36
    res.status(500).send(err.message);
    37
    return;
    38
    }
    39
    ​
    40
    data.forEach((ip) => {
    41
    iplist += `${ip}; `;
    42
    });
    43
    ​
    44
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    45
    res.end(iplist);
    46
    });
    47
    }).listen(process.env.PORT || 8080);
    48
    ​
    49
    console.log('started web process');
    Copied!

Run the app on your local computer

    1.
    Run the app with the following command:
    1
    npm start
    Copied!
    2.
    Visit http://localhost:8080 to see the app.
When you're ready to move forward, press Ctrl+C to stop the local web server.

Deploy

    1.
    Create an app.yaml file with the following content:
    1
    runtime: nodejs
    2
    env: flex
    Copied!
    2.
    Run the following command to deploy your app:
    1
    gcloud app deploy
    Copied!
    3.
    View the deployed app:
    1
    gcloud app browse
    Copied!
Last modified 6mo ago