Running Rails on the Cloud Run environment
Stay organized with collections
Save and categorize content based on your preferences.
Learn how to deploy a sample Rails application to
Cloud Run and how to integrate managed databases,
object storage, encrypted secrets, and build pipelines with serverless compute.
Deploying Rails applications involves integrating multiple services together to
form a cohesive project. This tutorial assumes that you are familiar with Rails
web development.
Diagram showing the architecture of the deployment.
The Rails site is served from Cloud Run, which uses multiple
backing services to store different data types (relational database
information, media assets, configuration secrets, and container images).
The backend services are updated by Cloud Build as part of a
build and migrate task.
Objectives
Create and connect a Cloud SQL database to Active Record
Create and use Secret Manager to store and access a Rails
master key securely
Host user-uploaded media and files on Cloud Storage from Active Storage
Use Cloud Build to automate build and database migrations
Deploy a Rails app to Cloud Run
Costs
Before you begin
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get 300ドル in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Roles required to select or create a project
Select a project: Selecting a project doesn't require a specific
IAM role—you can select any project that you've been
granted a role on.
Create a project: To create a project, you need the Project Creator role
(roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
Enable the Cloud Run, Cloud SQL, Cloud Build, Secret Manager, and Compute Engine APIs.
Roles required to enable APIs
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
To initialize the gcloud CLI, run the following command:
gcloudinit
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Roles required to select or create a project
Select a project: Selecting a project doesn't require a specific
IAM role—you can select any project that you've been
granted a role on.
Create a project: To create a project, you need the Project Creator role
(roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
Enable the Cloud Run, Cloud SQL, Cloud Build, Secret Manager, and Compute Engine APIs.
Roles required to enable APIs
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
To initialize the gcloud CLI, run the following command:
gcloudinit
Ensure sufficient permissions are available to the account used for this tutorial.
Prepare your environment
This tutorial uses several Google Cloud services to provide the
database, media storage, and secret storage that support the deployed Rails
application. Prepare your environment by configuring a region to deploy the
services in and by cloning the Rails app.
Set the default project and region
Set the default project configuration for the gcloud CLI by running
the following command:
gcloudconfigsetprojectPROJECT_ID
Replace PROJECT_ID with your Google Cloud
project ID
Configure your region:
exportREGION=REGION
Replace REGION with an appropriate location. For
efficiency between services, all services should be deployed in the same
region. For more information about the closest region to you, see
Products available by location.
Go to the directory that contains the sample code and run the following
commands to make sure that the application is properly set up with the
required gems and dependencies:
This tutorial uses a number of Google Cloud services to provide the
database, media storage, and secret storage that support the deployed Rails
project. These services are deployed in a specific region. For efficiency between
services, it is best that all services are deployed in the same region.
For more information about the closest region to you, see
Products available by location.
Set up a Cloud SQL for PostgreSQL instance
Rails supports multiple relational databases, including several offered by
Cloud SQL. This tutorial uses PostgreSQL, an open source database
commonly used by Rails apps.
The following sections describe the creation of a PostgreSQL instance, database,
and database user for your Rails app.
Now that the backing services are configured, Rails needs secure information, such as passwords, to access these services.
Instead of putting these values directly into the Rails source code, this tutorial uses Rails Credentials and
Secret Manager to store this information securely.
Create encrypted credentials file and store key as Secret Manager secret
Rails stores secrets in an encrypted file called 'config/credentials.yml.enc'.
The file can be decrypted with the local config/master.key or the environment
variable ENV["RAILS_MASTER_KEY"]. In the credentials file, you can store the
Cloud SQL instance database password and other access keys for external APIs.
You can store this key securely in Secret Manager. Then, you can grant
Cloud Run and Cloud Build access to the key by granting access to
their respective service accounts.
Service accounts are identified by an email address that contains the
project number.
Generate the config/credentials.yml.enc file with the following command:
bin/railscredentials:edit
The command will create a config/master.key if no master key is defined, and create a config/credentials.yml.enc file if the file does not exist.
This will open a temporary file in your default $EDITOR with the decrypted contents for the secrets to be added.
Copy and paste the newly created PostgreSQL instance database password from
the dbpassword file into the credentials file:
Secrets can be accessed with Rails.application.credentials. For example,
Rails.application.credentials.secret_key_base should return the
application's secret key base and
Rails.application.credentials.gcp[:db_password] should return your database
password.
The config/credentials/yml.enc is stored encrypted, but config/master.key
can be stored in Secret Manager.
Connect Rails app to production database and storage
This tutorial uses a PostgreSQL instance as the production database and
Cloud Storage as the storage backend. For Rails to connect to the
newly created database and storage bucket, you need to specify all the
information needed to access them in the .env file. The .env file contains
the configuration for the application environment variables. The application
will read this file using the dotenv gem. Since the secrets are stored in
credentials.yml.enc and Secret Manager, the .env doesn't
have to be encrypted because it doesn't hold any sensitive credentials.
To configure the Rails app to connect with the database and storage bucket,
open the .env file.
Modify the .env file configuration to the following. Use the value of
MEDIA_BUCKET_SUFFIX that you used when you created
the bucket.
Replace SERVICE_NAME with the name for your service. This first build takes a few minutes to complete. If the build timed out, increase the timeout duration by inserting --timeout=2000s into the build command.
When the build is successful, deploy the Cloud Run service for the
first time, setting the service region, base image, and connected Cloud SQL instance:
The Rails sample app was created using standard Rails commands. The following
commands create the cat_album app and use the scaffold command to generate a
model, controller, and views for the Photo resource:
The config/database.yml file contains the configuration needed to access
your databases in different environments (development, test, production). For
example, the production database is configured to run in Cloud SQL
for PostgreSQL. The database name and username are set through environment
variables in the .env file, while the database password is stored inside the
config/credentials.yml.enc file, which requires the RAILS_MASTER_KEY to
decrypt.
When the app runs on Cloud Run (fully managed), it connects
to the PostgreSQL instance using a socket provided by the
Cloud Run environment.
When the app runs on your local machine, it connects to the PostgreSQL
instance using the Cloud SQL Auth proxy.
Rails uses
Active Storage to
upload files to storage providers. The config/storage.yml and
config/environments/production.rb files specify Cloud Storage as the
service provider in the production environment.
# Store uploaded files on the local file system (see config/storage.yml for options).config.active_storage.service=:google
Automation with Cloud Build
The cloudbuild.yaml file performs not
only the typical image build steps (creating the container image and pushing
that to Artifact Registry), but also the Rails database migrations. This migration is
performed by using Cloud Run jobs, where a custom command is used so
that the container performs the migration, rather than the default web server.
steps:-id:"buildimage"name:"gcr.io/cloud-builders/docker"entrypoint:'bash'args:["-c","dockerbuild--build-argMASTER_KEY=$$RAILS_KEY-t${_IMAGE_NAME}."]secretEnv:["RAILS_KEY"]-id:"pushimage"name:"gcr.io/cloud-builders/docker"args:["push","${_IMAGE_NAME}"]-id:"applymigrations"name:"gcr.io/google.com/cloudsdktool/cloud-sdk"entrypoint:/bin/bashsecretEnv:["RAILS_KEY"]args:-"-c"-|gcloud run jobs create migrate-job \--region ${_REGION} \--image ${_IMAGE_NAME} \--set-cloudsql-instances ${_CLOUD_SQL_CONNECTION_NAME} \--set-env-vars RAILS_MASTER_KEY=$$RAILS_KEY \--command bundle \--args exec,rails,db:migrate \--execute-now --wait && \gcloud run jobs delete migrate-job --region ${_REGION} -qoptions:dynamicSubstitutions:truesubstitutions:_REGION:us-central1_SERVICE_NAME:rails-cat-album_INSTANCE_NAME:cat-album_SECRET_NAME:rails-master-key_AR_REPO_NAME:cloud-run-source-deploy_IMAGE_NAME:${_REGION}-docker.pkg.dev/${PROJECT_ID}/${_AR_REPO_NAME}/${_SERVICE_NAME}_CLOUD_SQL_CONNECTION_NAME:${PROJECT_ID}:${_REGION}:${_INSTANCE_NAME}availableSecrets:secretManager:-versionName:projects/${PROJECT_ID}/secrets/${_SECRET_NAME}/versions/latestenv:RAILS_KEYimages:-"${_IMAGE_NAME}"
Substitution variables are used in this configuration. Changing the values in the file directly means the --substitutions flag can be dropped at migration time.
In this configuration, only existing migrations in the db/migrate directory
are applied. To create migration files, see
Active Record Migrations.
To build the image and apply migrations, the
Cloud Build configuration
needs access to the RAILS_MASTER_KEY secret from Secret Manager. The availableSecrets field sets the secret version and environment variables to use for the secret. The master key secret is passed in as an argument in the build image step and then gets set to be the RAILS_MASTER_KEY in the Dockerfile when building the image.
ARGMASTER_KEY
ENVRAILS_MASTER_KEY=${MASTER_KEY}
To extend the Cloud Build configuration to include the deployment
in the one configuration without having to run two commands, see
Continuous deployment from git using Cloud Build. This requires IAM changes, as described.
Cloud Logging and Error Reporting
By default, Rails logs to stdout in production when configured with
RAILS_LOG_TO_STDOUT. When your application runs on
Cloud Run, the environment automatically captures logs written
to stdout and stderr and stores them in Cloud Logging.
To automatically capture unhandled exceptions and display formatted stack
traces in Error Reporting, add the google-cloud-error_reporting
gem to your Gemfile:
gem"google-cloud-error_reporting"
When your Rails application starts in production mode, Bundler automatically
loads the library and configures Error Reporting to capture
exceptions from the Rack stack. For more information, see
Setting Up Error Reporting for
Ruby.
Cleanup
In the Google Cloud console, go to the Manage resources page.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026年08月26日 UTC."],[],[]]