Docker Compose + Spring Boot + Postgres connection

后端 未结 3 1596
孤街浪徒
孤街浪徒 2021-02-12 17:15

I have a Java Spring Boot app which works with a Postgres database. I want to use Docker for both of them. I initially put just the Postgres in Docker, and I had a docker-

3条回答
  •  悲&欢浪女
    2021-02-12 17:19

    I had the same problem and I lost some time to understand and solve this problem:

    org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
    

    I show all the properties so that everyone understands.
    application.properties:

    spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
    spring.datasource.driver-class-name=org.postgresql.Driver
    spring.datasource.username=postgres
    spring.datasource.password=postgres
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL82Dialect
    spring.jpa.hibernate.ddl-auto=update
    

    docker-compose.yml:

      version: "3"
      services:
        springapp:
          build: .
          container_name: springapp
          environment:
            SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/testdb
          ports:
            - 8000:8080
          restart: always
          depends_on:
            - db
        db:
          image: postgres
          container_name: db
          environment:
            - POSTGRES_USER=postgres
            - POSTGRES_PASSWORD=postgres
            - POSTGRES_DB=testdb
            - PGDATA=/var/lib/postgresql/data/pgdata
          ports:
            - 5000:5432
          volumes:
            - pgdata:/var/lib/postgresql/data
          restart: always
      volumes:
        pgdata:
    

    For start spring application with local database we use url localhost.
    For connect to container with database we need change 'localhost' on your database service, in my case 'localhost' to 'db'.

    Solution: add SPRING_DATASOURCE_URL environment in docker-compose.yml wich rewrite spring.datasource.url value for connect:

      environment:
        SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/testdb
    

    I hope this helps someone save his time.

提交回复
热议问题