I am evaluating Spring 4 on Heroku and I am so far very impressed with both.
However, I am having trouble getting my Spring Boot app to run on Heroku. Everything is working fine, except Postgresql (I just get Connection Refused
errors).
The problem will surely be to do with how I am setting up the DataSource
but so far I've just been following a trial and error approach! I am not exactly sure how I am supposed to set-up the data source from the Heroku DATABASE_URL
and I can't find any examples.
I have found spring-cloud by chance by searching on Google which looks promising but it doesn't explained anything about the DATABASE_URL
. Also, it isn't even mentioned on Spring.IO so I am wondering if it is even an option for production use?
You can use Config Vars which can be configured in the settings tab of your application at Heroku. The Config Vars will be exposed as environment variables to your application. Since Spring Boot can map environment variables to application properties you just need to set:
SPRING_DATASOURCE_URL
SPRING_DATASOURCE_USER
SPRING_DATASOURCE_PASSWORD
SPRING_DATASOURCE_DRIVER-CLASS-NAME
And they will be mapped to:
spring.datasource.url
spring.datasource.user
spring.datasource.password
spring.datasource.driver-class-name
Now all you have to do is to extract the relevant values. The complete data base configuration can be inspected at the heroku postgres management panel. Select the data base you want to connect to and you will see the values for SPRING_DATASOURCE_USER
and SPRING_DATASOURCE_PASSWORD
right away. The SPRING_DATASOURCE_URL
has to be constructed like this:
jdbc:postgresql://<Host>:<Port>/<Database>
Where <Host>
, <Port>
and <Database>
have to replaced by the corresponding values from the data base connection page. Last but not least the SPRING_DATASOURCE_DRIVER-CLASS-NAME
has to be set to org.postgresql.Driver
.
This way you can use the build in functionality of Spring Boot instead of adding environment specific configuration to your application. Note however, that Spring Boot has a specific order of reading external configuration. So you have to make sure there are no
-D
arguments)since those would override the OS environment variables.
One thing I would like to add after struggling with this for a while - just creating a configuration object is not sufficient with Heroku, even with the spring cloud connectors. You also have to explicitly declare the cloud profile (-Dspring.profiles.active=cloud
) in your application Procfile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With