How to use both Java in Docker and PostgreSQL database?

老子叫甜甜 提交于 2021-01-29 08:08:16

问题


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?


回答1:


How can I connect to PostgreSQL from Java in Docker on Heroku?

Relevant documentation can be found at the following URL:

https://devcenter.heroku.com/articles/heroku-postgresql#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 (or JDBC_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:

version: '3'
services:
  db:
    image: 'postgres:12'
    # v12 → https://devcenter.heroku.com/articles/heroku-postgresql#version-support
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: TestPhasePassword
      POSTGRES_DB: mydb
    # The following is UNNEEDED for the app service to access the db.
    # Enable it ONLY IF YOU NEED TO ALSO ACCESS THE DB FROM THE HOST.
    # ports:
    #   - '5432:5432'
    networks:
      - db-net
  app:
    build: .
    # image: name-of-your-app  # optional
    environment:
      DATABASE_URL: 'postgres://postgres:TestPhasePassword@db/mydb'
    ports:
      - '8080:8080'
    networks:
      - db-net
    depends_on:
      - db
networks:
  db-net:
    driver: bridge

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 the app image…



来源:https://stackoverflow.com/questions/64759269/how-to-use-both-java-in-docker-and-postgresql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!