从访客 vagrant box 连接到主机上 docker 中的 postgres 数据库

Connect to postgres db in docker on host from guest vagrant box

不确定这是否可行,但我的 macbook 上的 VirtualBox 中有一个 Vagrant box 运行 ubuntu 18.04 运行。我的 mac 上还有一个 docker 容器 运行,里面有一个 postgres 数据库。

我希望能够从 ubuntu 中连接到 docker 中的数据库。

我的第一次尝试是将以下内容添加到我的 VagrantFile

config.vm.network "forwarded_port", guest: 5432, host: 5432

然而,这导致了以下错误:

Vagrant cannot forward the specified ports on this VM, since they
would collide with some other application that is already listening
on these ports. The forwarded port to 5432 is already in use
on the host machine.

To fix this, modify your current project's Vagrantfile to use another
port. Example, where '1234' would be replaced by a unique host port:

  config.vm.network :forwarded_port, guest: 5432, host: 1234

Sometimes, Vagrant will attempt to auto-correct this for you. In this
case, Vagrant was unable to. This is usually because the guest machine
is in a state which doesn't allow modifying port forwarding. You could
try 'vagrant reload' (equivalent of running a halt followed by an up)
so vagrant can attempt to auto-correct this upon booting. Be warned
that any unsaved work might be lost.

我理解这个错误,这很合理,因为主机已经在监听端口 5432(或者更确切地说 docker/postgres 容器)。但我不知道如何解决这个问题。如果我按照建议更改主机端口号,它将无法工作,因为那样我就无法连接到正确的端口。

建议?

我明白了。其实很简单。

你看,docker postgres 数据库在 HOST 机器上的 'localhost' 或 '127.0.0.1' 可用,但 HOST 机器出于某种原因出现在 10.0.2.2 给 GUEST机器。我所要做的就是将我的数据库连接脚本指向 10.0.2.2,不需要额外的网络配置。