如何从docker-compose连接到主机上的PostgreSQL?

12

我有一个安装了PostgreSQL的服务器。所有的服务都在容器中运行(使用docker-compose)。我想从容器中使用我的主机上的PostgreSQL,但是出现了错误:

  Unable to obtain Jdbc connection from DataSource (jdbc:postgresql://localhost:5432/shop-bd) for user 'shop-bd-user': Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
  ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  SQL State  : 08001
  Error Code : 0
  Message    : Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

  Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
  Connection refused (Connection refused)

我的docker-compose正在使用主机网络模式,就像这样:

version: '3'
services:
  shop:  
    container_name: shop
    build: ./shop
    hostname: shop
    restart: always   
    ports:
      - 8084:8084
    network_mode: "host"

我的数据库连接URL是:jdbc:postgresql://localhost:5432/shop-bd


你正在要求Docker将端口8084:8084映射,但你没有提及端口5432 - jimmu
@Krishna 8084 是该服务的端口。其他服务可以通过 http://localhost:8084 与此服务通信。但对于主机DB不起作用。 - Max
展示一下你的 db 服务的配置是什么样子的。它应该在端口下面有 5432:5432 - jimmu
你在哪个操作系统上使用Docker? - Tarun Lalwani
1
@TarunLalwani 我在Windows上开发。 - Max
5个回答

29
根据文档,从18.03版本开始,使用host.docker.internal作为DNS对我来说是有效的,无需指定--net=hostnetwork_mode: "host"

1
非常有帮助。请点赞并接受这个答案! - Brendan Goggin
@BrendanGoggin 当然。 - Max
注意:使用 --net=host 或 network_mode: "host" 会阻止您的容器在Eureka中注册,并且会破坏任何API网关,除非它们都运行在同一个网络上。 - MikeBFromPDX
6
此为开发目的,不适用于 Docker Desktop for Mac 之外的生产环境。 - 030

6

如果您使用的是Linux操作系统,那么这个方法是可行的。但是在Mac或Windows上不起作用。问题在于当您使用--net=host时,您仍然不在主机网络上。这是Docker for Windows工作方式的限制。

您需要使用docker.for.win.localhost代替localhost作为主机名。这是一个特殊的DNS名称,在Docker for Windows中可用,用于引用主机localhost。


4
如果您是Mac用户,请使用“host.docker.internal:5432”连接到本地Postgres,docs

0

注意:使用--net=host或network_mode: "host"将阻止您的容器向Eureka注册,并且会破坏任何API网关,除非它们都在同一网络上运行。


-3

1) 确保您的PostgreSQL实例正在监听所有地址,而不仅仅是本地主机。

在postgresql.conf中设置listen_addresses如下:

listen_addresses='*'

2) 你正在尝试从容器连接到 localhost:5432。那不是你主机的IP地址,而是你容器的loopback设备的地址。你需要使用你的Docker桥接IP地址。


我使用--net=host,所以可以使用localhost。我认为问题是由于Windows引起的。 - Max
是的,你说得对,我错过了你正在使用主机网络。 - whites11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接