Connecting to Heroku Postgres Databases from Outside of Heroku
Last updated 25 January 2017
Heroku Postgres databases are designed to be used with a Heroku app. However, they are accessible from anywhere and may be used from any application using standard Postgres clients.
To make effective use of Heroku Postgres databases outside of a Heroku application, keep in mind the following:
All Heroku Postgres databases have a corresponding Heroku application. You can find the application name on the database page at data.heroku.com. You do not have to use the Heroku app for application code, but your database is attached to it and holds a config var containing the database URL. This variable is managed by Heroku, and is the primary way we tell you about your database’s network location and credentials.
Do not copy and paste database credentials to a separate environment or into your application’s code. The database URL is managed by Heroku and will change under some circumstances such as:
- User initiated database credential rotations using
heroku pg:credentials --reset.
- Catastrophic hardware failure leading to Heroku Postgres staff recovering your database on new hardware.
- Automated failover events on HA enabled plans.
It is best practice to always fetch the database URL config var from the corresponding Heroku app when your application starts. For example, you may follow 12Factor application configuration principles by using the Heroku CLI and invoke your process like so:
DATABASE_URL=$(heroku config:get DATABASE_URL -a your-app) your_process
This way, you ensure your process or application always has correct database credentials.
Other Heroku Apps
If you need to connect to a database from other Heroku apps, you can now attach a database addon directly to multiple applications. This ensures that any changes to the database’s URL will automatically propagate to your other apps.
Applications outside of the Heroku network must support and enable SSL to connect to a Heroku Postgres database. Most clients connect over SSL by default, but sometimes it’s necessary to add the
sslmode=require query parameter to your database URL before connecting. Clients using libpq or postgresql libraries version 9.2 or older might not be supported, due to changes in SSL security.
Be sure to append the
sslmode=require parameter to your database’s URL from code, rather than by editing the value of your
DATABASE_URL config var directly. Various automated events (such as a failover) can change the value of the config var, which overwrites any edits you make.
You can use Heroku Postgres Backups on the enclosing Heroku app in order to get automated backups on your database. Heroku Postgres Backups takes backups of the database pointed at by
DATABASE_URL in the Heroku app, so make sure you promote your database:
heroku pg:promote HEROKU_POSTGRESQL_VIOLET --app your-app