[英]Connect to postgres db in docker on host from guest vagrant box
Not sure if this is possible, but I have a Vagrant box running ubuntu 18.04 running in VirtualBox on my macbook. 不知道这是否可能,但是我在Macbook上的VirtualBox中有一个运行ubuntu 18.04的Vagrant盒。 I also have a docker container running on my mac which has a postgres database in it.
我也有一个在我的Mac上运行的docker容器,其中有一个postgres数据库。
I would like to be able to connect from within ubuntu to the database in docker. 我希望能够从ubuntu内部连接到docker中的数据库。
My first attempt at this was to add the following to my VagrantFile 我的第一次尝试是将以下内容添加到我的VagrantFile中
config.vm.network "forwarded_port", guest: 5432, host: 5432
However that resulted in the following error: 但是,这导致以下错误:
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.
I understand the error, it makes perfect sense because the host is already listening to port 5432 (or rather the docker/postgres container is). 我理解该错误,因为主机已经在侦听端口5432(或更确切地说是docker / postgres容器),所以这很有意义。 but i don't know how to fix the problem.
但是我不知道如何解决这个问题。 If i do as suggested and change the host port number it would not work because then I wouldn't be connecting to the right port.
如果我按照建议进行操作并更改主机端口号,它将无法正常工作,因为那样我就无法连接到正确的端口。
Suggestions? 有什么建议吗?
I figured it out. 我想到了。 it's pretty easy actually.
实际上这很容易。
You see, the docker postgres db is availabe at 'localhost' or '127.0.0.1' on the HOST machine, but the HOST machine appears at 10.0.2.2 for some reason to the GUEST machine. 您会看到,docker postgres db位于HOST机器上的“ localhost”或“ 127.0.0.1”,但是出于某些原因,GUEST机器上的HOST机器显示为10.0.2.2。 All i had to do was point my database connect script to 10.0.2.2 and no extra network config was needed.
我要做的就是将我的数据库连接脚本指向10.0.2.2,并且不需要额外的网络配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.