Spring Docker容器无法访问Postgres Docker容器 [英] Spring Docker container cannot access Postgres Docker container

查看:275
本文介绍了Spring Docker容器无法访问Postgres Docker容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的春季启动应用程序的Dockerfile:

The Dockerfile of my spring-boot app:

FROM openjdk:8-jdk-alpine
VOLUME /tmp
COPY target/media-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

application.yml

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/media
    username: postgres
    password: postgres
    hikari:
      connectionTimeout: 30000

这是 docker-compose.yml

version: '3'
services:
  db:
    image: postgres
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: media
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres

  app:
    build:
      context: ./
      dockerfile: Dockerfile
    depends_on:
      - db
    ports:
      - "8080:8080"

运行 docker-compose up --build 结果为:


app_1 | org.postgresql.util.PSQLException:拒绝连接到0.0.0.0:5432
。检查主机名和端口是否正确以及
邮件管理员正在接受TCP / IP连接。 app_1

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

我的猜测是spring应用程序在postgres准备好之前尝试连接到postgres,但我得到以下日志:

My guess is that the spring app tries to connect to postgres before postgres is ready, but I get the following log:


db_1 | 2019-05-18 19:05:53.692 UTC [1]日志:数据库系统已准备好
接受连接

db_1 | 2019-05-18 19:05:53.692 UTC [1] LOG: database system is ready to accept connections


推荐答案

Docker Compose的主要目的是启动一组Docker容器,它们将作为独立实体运行。默认情况下,所有容器都将与其他所有容器建立虚拟网络连接,不过您可以根据需要进行更改。您将获得该功能,因为您尚未指定自定义配置。

The main purpose of Docker Compose is to spin up a set of Docker containers, which will then function as independent entities. By default, all containers will have a virtual network connection to all others, though you can change that if you wish; you will get that feature, since you have not specified a custom configuration.

每个容器都将在Docker设置的虚拟网络内获得一个虚拟IP地址。由于这些是动态的,因此Docker Compose通过创建与每个服务相对应的内部DNS条目使您更轻松。因此,您将有两个容器,它们可以分别来自于另一个容器,也可以分别称为 app db 。如果安装了ping,也可以通过 docker-compose exec 或通过手动创建的shell来ping这些名称。

Each of the containers will get a virtual IP address inside the virtual network set up by Docker. Since these are dynamic, Docker Compose makes it easier for you by creating internal DNS entries corresponding to each service. So, you will have two containers, which can be addressed as app and db respectively, either from themselves or the other. If you have ping installed, you can ping these names too, either via docker-compose exec, or via a manually-created shell.

因此,正如我们在评论中发现的那样,您可以从 app 连接到 jdbc:postgresql:// db:5432 /媒体,它应该可以正常工作。

Thus, as we discovered in the comments, you can connect from app to jdbc:postgresql://db:5432/media, and it should work.

这篇关于Spring Docker容器无法访问Postgres Docker容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆