You can connect to a Redis instance from Cloud Run by using Direct VPC egress.
Setup
If you have already installed the Google Cloud CLI and have created a Redis instance, you can skip these steps.
Install the gcloud CLI and initialize:
gcloud initFollow the Quickstart Guide to create a Redis instance. Take note of the zone, IP address, and port of the Redis instance.
Prepare VPC network egress for configuration
To connect to your Redis instance, your Cloud Run service must have access to the Redis instance's authorized VPC network.
To find the name of this network, run the following command:
gcloud redis instances describe INSTANCE_ID --region REGION --format "value(authorizedNetwork)"
Make a note of the network name.
Sample application
This sample HTTP server application establishes a connection to a Redis instance from a Cloud Run service.
Clone the repository for your chosen programming language and navigate to the folder that contains the sample code:
Go
git clone https://github.com/GoogleCloudPlatform/golang-samples
cd golang-samples/memorystore/redis
Node.js
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/memorystore/redis
Python
git clone https://github.com/GoogleCloudPlatform/python-docs-samples
cd python-docs-samples/memorystore/redis
This sample application increments a Redis counter every time the / endpoint
is accessed.
Go
This application uses the
github.com/gomodule/redigo/redis
client. Install it by running the following command:
go get github.com/gomodule/redigo/redis
Node.js
This application uses the redis
module.
Python
This application uses Flask
for web serving and the redis-py
package to communicate with the Redis instance.
Deploying the application to Cloud Run
To deploy the application:
Copy the
Dockerfileinto the source directory:cp cloud_run_deployment/Dockerfile .Build a container image using Cloud Build by running the following command:
gcloud builds submit --tag gcr.io/PROJECT_ID/visit-count
Deploy the container to Cloud Run by running the following command:
gcloud run deploy \ --image gcr.io/PROJECT_ID/visit-count \ --allow-unauthenticated \ --region REGION \ --network NETWORK \ --subnet SUBNET \ --set-env-vars REDISHOST=REDIS_IP,REDISPORT=REDIS_PORTwhere:
PROJECT_IDis your Google Cloud project's ID.REGIONis the region where your Redis instance is located.NETWORKis the name of the authorized VPC network that your Redis instance is attached to.SUBNETis the name of your subnet. The subnet must be/26or larger. Direct VPC egress supports IPv4 ranges RFC 1918, RFC 6598, and Class E.REDIS_IPandREDIS_PORTare the IP address and port number of your Redis instance.
After the deployment successfully completes, the command line displays your
Cloud Run service's URL. Visit this URL in a web browser
(or use a tool like curl) and see the count on your Redis instance increase
each time the service is visited.