I am developing the Heroku toy app and want to use the PostgreSQL database to store configurations. I either see tutorials on how to use Java + PostgreSQL or Java on Docker.
I cannot find a way on how I can use Java in Docker + PostgreSQL.
NOTE: Database is a rather unimportant piece. It can be anything that can persist info such as Redis, other databases.
I looked through StackOverflow, tutorials, and Heroku doc but so far, no luck.
How can I connect to PostgreSQL from Java in Docker on Heroku?
2
Answers
To extend the @ErikMD answer, I have to add that there are many plugins for different databases available to establish the connection in the Java app, and there is no need to run Docker with DB inside but rather rely on plugins vendors.
I tried MySQL, PostgreSQL and never got any troubles with DB. If you move with plugins solutions, check their pricing model and limitations to avoid getting into billing trouble. Also, some plugins provide older databases, and you may have to put more effort into resolving correct library versions.
GUIDE:
heroku config -a <app_name>
to obtain db credentialsapplication.properties
orapplication.yml
Relevant documentation can be found at the following URL:
https://devcenter.heroku.com/articles/connecting-heroku-postgres#connecting-in-java
To sum up, Heroku provides native support for PostgreSQL (independently of Docker) and your Java application can connect to the database by means of a dedicated environment variable
DATABASE_URL
(orJDBC_DATABASE_URL
), which should be exported as a Docker container environment variable in your case, deploying your app via Heroku’s Docker container registry.This is in line with Docker’s best practices regarding access to external databases, namely, the PostgreSQL database is not part of the app container, but the app container communicates with the database via HTTP requests.
Additional details
Furthermore, if you are interested in CI/CD or in fully testing locally your app with a complete dev configuration involving a copy (or a stub) of your PostgreSQL database, let me note that you might be interested in devising a
docker-compose.yml
configuration, such as the following:and just run
docker-compose up
.So here, the
db
service is just a dev/test instance… given the only image intended to be pushed/released in Heroku is theapp
image…