Home > Net >  How dockerize Spring Boot app if Postgres db is going to be AWS RDS?
How dockerize Spring Boot app if Postgres db is going to be AWS RDS?

Time:10-22

    version: "3.7"
services:
  api_service:
    build: .
    restart: always
    ports:
      - 8080:8080
    depends_on:
      - postgres_db
    links:
      - postgres_db:database
  postgres_db:
    image: "postgres:11.4"
    restart: always
    ports:
      - 5435:5432
    environment:
      POSTGRES_DB: testDb
      POSTGRES_PASSWORD: admin

this is my yaml

and I got properties

spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://database:5432/testDb
spring.datasource.username=postgres
spring.datasource.password=admin

if my postgres is rds then do I need to compose them or I just can go with dockerfile for jar only and not yaml file?

CodePudding user response:

You can create environment variables for the RDS address, RDS username, RDS password and RDS port. Pass it to the Dockerfile to the api_service. Your api_service should know to assemble Postgres connection string based on the environment variables. Please check - Spring Profiles in connection String

CodePudding user response:

Those Spring properties values are probably incorrect in most of the environments in which you might run your application. In your unit-test environment the database might be H2 or HDBC instead of PostgreSQL; in a local-developer setup it will be on localhost; in RDS it will be a different name again. These host names and credentials should not be in your src/main/resources tree anywhere.

Spring allows you to set Spring properties using environment variables. So you can set e.g. spring.datasource.url at the point where you deploy your application. In your Compose setup, for example:

version: "3.8"
services:
  api_service:
    build: .
    restart: always
    ports:
      - 8080:8080
    depends_on:
      - postgres_db
    environment:
      - SPRING_DATASOURCE_URL=jdbc:postgresql://postgres_db:5432/testDb
      - SPRING_DATASOURCE_USERNAME=postgres
      - SPRING_DATASOURCE_PASSWORD=admin
  postgres_db:
    image: "postgres:11.4"
    restart: always
    ports:
      - 5435:5432
    environment:
      POSTGRES_DB: testDb
      POSTGRES_PASSWORD: admin

If your production environment uses RDS, then it should be enough to remove the postgres_db container and change the SPRING_DATASOURCE_* environment variables to match the RDS host name and credentials. You don't have to recompile anything or change the contents of your jar file.

  • Related