Google Cloud SQL + Heroku + Rails
So you have a Google Cloud SQL running postgres and you want to use it on Heroku. No problem. I'll walk you through how to do it with a rails application.
- Add the Heroku Google Cloud SQL Proxy Buildpack
- Setup the Heroku env variables for the Google Cloud SQL Proxy
- Setup Rails Procfile and database.yml
Heroku
Add the Google Cloud SQL Proxy Buildpack
From your terminal using the Heroku CLI
heroku buildpacks:add --index=1 https://github.com/lukelove/heroku-buildpack-cloud-sql-proxy.git
Google Cloud SQL
Follow the Setup and installation for this buildpack making sure to add all of the env variables to your project.
Rails
Procfile
Your Procfile should look something like this.
web: bin/run_cloud_sql_proxy &>null && bundle exec rails server -p $PORT
rake: bin/run_cloud_sql_proxy &>null && rake
rails: bin/run_cloud_sql_proxy &>null && bundle exec rails
Make sure that the bin/run_cloud_sql_proxy
is always run before your desired actions. This will enable you to run things like normal ie:
> heroku run rails console
> heroku run rake db:migrate
Database
Remove the production
environment from config/database.yml
which forces heroku to use the DATABASE_URL
env variable.
If you just created a new app, Heroku automatically assigns it a database and sets the DATABASE_URL
. If it's appropriate for you, remove the empty database from the Heroku project resources since you'll be using the Google Cloud SQL anyways.