Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share database between 2 apps in Heroku

I want to access the database of an app from another Heroku app. Is that possible in the shared database?

like image 941
donald Avatar asked May 12 '11 16:05

donald


People also ask

Can you host a database on Heroku?

Heroku offers a free plan for hosting PostgreSQL databases. This can be handy if you're getting started with a new project or "just quickly need a hosted database" for experimentation or prototyping.


2 Answers

UPDATED

Originally, this answer stated that although this was possible with a few tricks, it was strongly discouraged. This was based on advice on the Heroku developer support website. However, recently Heroku issued a communication specifically describing how to achieve this, and have watered down their advice on the developer site. The complete text of this section of their e-mail is included below:

Did you know that Heroku apps can share a common database? For example, you can put analytics functions in a separate application from your user-facing code.

Simply set the DATABASE_URL config var for several apps to the same value. First, get the DATABASE_URL for your existing app:

$ heroku config | grep DATABASE_URL  --app sushi DATABASE_URL => postgres://lswlmfdsfos:[email protected]/ldfoiusfsf 

Then, set the DATABASE_URL for new apps to this value:

$ heroku config:add DATABASE_URL=postgres://lswlmfdsfos:[email protected]/ldfoiusfsf --app sushi-analytics Adding config vars: DATABASE_URL => postgres://lswlm...m/ldfoiusfsf Restarting app... done, v74. That's it 

— now both apps will share one database.

Just as a point of reference, Heroku's original advice was to create and use an API to access data remotely. My personal view is that overall, for many situations this is good advice, (i.e. better than just connecting multiple application to the same DB) although I can see situations where that'd be more trouble than it's worth.

UPDATE

As per comments on this answer, it's worth noting that Heroku do reserve the right to change database URLs as required. If this occurs, it will cause your secondary connections to fail, and you'll need to update the URLs accordingly.

like image 164
Paul Russell Avatar answered Sep 18 '22 04:09

Paul Russell


Late-breaking answer to the pertinent question!

Heroku officially supports a better/graceful solution by the way of their addon framework now. It is described in their latest newsletter on how to share addons between apps. Below are the snippets mentioned in the writeup:

$ heroku addons:attach my-sushi-db -a my-sushi-reporting --as MAIN_SUSHI_DB       Adding MAIN_SUSHI_DB to my-sushi-reporting... done   Setting MAIN_SUSHI_DB vars and restarting my-sushi-app-reporting... done, v3 

Link: expanding_the_power_of_add_ons

like image 28
c360ian Avatar answered Sep 21 '22 04:09

c360ian