Spring Boot,PostgreSQL和Docker - 拒绝连接在容器中运行

时间:2018-01-20 19:01:14

标签: spring postgresql docker spring-boot docker-compose

我正在尝试构建一个由Spring Boot应用程序和PostgreSQL数据库组成的“服务”。当Spring Boot应用程序在我的本地计算机上运行时,我能够从Spring Boot应用程序访问数据库(在容器中运行)。现在,当我尝试将Spring Boot应用程序移动到容器时,我收到以下错误:

kind

但是,我可以从本地计算机连接到DB: inventory_1 | 2018-01-20 18:43:06.108 ERROR 1 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection] with root cause inventory_1 | inventory_1 | java.net.ConnectException: Connection refused (Connection refused)

我的application.properties文件:

psql -h localhost -p 5000 -U kelly_psql -d leisurely_diversion

我的docker-compose文件:

spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.url=jdbc:postgresql://localhost:5432/leisurely_diversion
spring.datasource.username=kelly_psql
spring.datasource.password=pass
spring.datasource.driver-class-name=org.postgresql.Driver

我的Dockerfile(来自Spring website

    # Use postgres/example user/password credentials
version: '3.2'

services:
  db:
    image: postgres
    ports:
      - 5000:5432
    environment:
      POSTGRES_PASSWORD: example
    volumes:
      - type: volume
        source: psql_data
        target: /var/lib/postgresql/data
    networks: 
      - app
    restart: always
  inventory:
    image: kellymarchewa/inventory_api
    depends_on:
        - db
    ports:
      - 8080:8080
    networks:
      - app
    restart: always
volumes:
  psql_data:
networks: 
  app:

我怀疑问题在于(对我来说)Docker或容器的误解,但我不确定。任何建议将不胜感激。

3 个答案:

答案 0 :(得分:2)

您将应用程序指向*(*(pp + i) + j),但容器之间不会共享。

要访问其他容器,您必须引用其localhost

在您的情况下,我们了解您希望hostname服务访问inventory服务。因此,您应该使用以下db网址:

datasource

请参阅此简单教程,了解如何使用docker compose从另一个容器连接到容器:https://docs.docker.com/compose/gettingstarted/

答案 1 :(得分:1)

就我而言,如果您在Windows 8.1上使用 Docker Toolbox ,则不能使用“ localhost”

相反,您必须使用docker machine ip;

 host> docker-machine ip default

 192.168.99.100

之后,您的网址将如下所示;

 spring.datasource.url=jdbc:postgresql://192.168.99.100:5432/bankdb

这将成功连接到Docker Postgres DB。

干杯!

答案 2 :(得分:0)

详细阐述了ESala给出的答案:

我同意,这是一个网络问题,并且给定的解决方案工作正常,但您也可以使用localhost(例如,如果您真的真的想要),通过在运行容器时切换到网络主机模式(cf here)。就像nginx完成here一样。

我说你大部分时间都不想要这个,因为它与你获得的沙箱相混淆。但是存在这个选择。

相关问题