从来宾游民游箱连接到主机上Docker中的PostgreSQL中的db

时间:2019-05-10 17:06:43

标签: postgresql docker vagrant vagrantfile

不确定这是否可行,但是我的Macbook上的VirtualBox中有一个运行ubuntu 18.04的Vagrant盒。我还在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容器正在侦听),所以这很有意义。但是我不知道如何解决这个问题。如果我按照建议的方式操作并更改了主机端口号,它将无法正常工作,因为那样我就无法连接到正确的端口。

建议?

1 个答案:

答案 0 :(得分:0)

我知道了。其实很简单。

您会看到,docker postgres db位于HOST计算机上的“ localhost”或“ 127.0.0.1”,但是出于某种原因,对于GUEST计算机而言,HOST计算机显示为10.0.2.2。我要做的就是将我的数据库连接脚本指向10.0.2.2,不需要额外的网络配置。