我正在构建我的第一个Springboot 2.0应用程序。我试图将Springboot应用程序放入一个docker容器中,并将PostgresDB放入另一个容器。

我的Dockerfile

    FROM frolvlad/alpine-oraclejdk8:slim
    VOLUME /tmp
    ADD springboot-api-demo-0.1*.jar app.jar
    RUN sh -c 'touch /app.jar'
    EXPOSE 9443
    ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/urandom -jar /app.jar" ]


我的docker-compose.yml文件

version: "2.1"

services:
  springboot-api-demo:
    image: "fw/springboot-api-demo"
    mem_limit: 1024m
    ports:
      - "8080:8080"
    environment:
      - SPRING_PROFILES_ACTIVE=local
      - AWS_REGION=local
      - ENVIRONMENT=local
      - AUTH_ENABLED=false
  postgres:
    container_name: pgdb
    image: postgres:9.6-alpine
    environment:
    - 'POSTGRES_ROOT_PASSWORD=postgres'
    - 'POSTGRES_USER=postgres'
    - 'POSTGRES_PASSWORD=postgres'
    ports:
    - "54321:5432"


我在我的application.properties中使用具有以下配置数据的Springboot JPA Data 2.0

spring.datasource.url= jdbc:postgresql://localhost:54321/java_learning
spring.datasource.username=postgres
spring.datasource.password=postgres


我可以测试两个图像都正常。同样从docker日志和docker事件中,我看到postgres Container运行良好,即使我可以访问它,也创建了一个数据库。
但是springboot容器启动了,但是我死了,因为它无法连接到postgress并在下面抛出错误。


无法从数据库获取连接:连接尝试
失败了


请注意,我的主机在端口5432上已经具有Postgres,这就是为什么我在postgres容器上进行了端口映射ofr 54321:5432的原因。这是证明:)-

➜  springboot-api-demo git:(master) ✗ lsof -i:54321
COMMAND     PID             USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
com.docke 44345 shailendra.singh   18u  IPv4 0xf62897fbdd69e31d      0t0  TCP *:54321 (LISTEN)
com.docke 44345 shailendra.singh   21u  IPv6 0xf62897fbdd119975      0t0  TCP localhost:54321 (LISTEN)

➜  springboot-api-demo git:(master) ✗ lsof -i:5432
COMMAND  PID             USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
postgres 715 shailendra.singh    5u  IPv6 0xf62897fbb43e03b5      0t0  TCP localhost:postgresql (LISTEN)
postgres 715 shailendra.singh    6u  IPv4 0xf62897fbbaeea9bd      0t0  TCP localhost:postgresql (LISTEN)


我不确定是什么问题。但是我的Springboot应用程序无法连接我的postgres容器,该容器可以正常运行并具有适当的凭据。

最佳答案

尝试:

spring.datasource.url= jdbc:postgresql://pgdb:5432/java_learning


postgres数据库未在localhost上运行,而是在具有另一个IP(但未知)的另一个容器中运行。

幸运的是,docker-compose会自动在docker-compose.yml中的所有容器之间创建一个共享的网络(除非明确表示不这样做),因此您可以神奇地将服务名用作主机名。

另外,您的端口中有错字,Postgres默认使用5432,而不是54321

09-17 07:56