在 Vagrant 的 Docker 容器中访问 PostgreSQL 运行

Access PostgreSQL running in Docker container in Vagrant

我有一个 Vagrant 盒子,其中有一个运行 PostgreSQL 的 Docker 容器。容器是官方找到的here

我希望能够使用 psql 从主机(即 Vagrant 外部)连接到 Postgres,但无法正常工作。 (得到一个 "could not connect"-错误)。我在我的 Vagrantfile 中添加了一个端口转发:

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

但我猜这还不够,因为 Docker 容器有自己的 IP (172.17.0.2)?我的想法是我会在盒子上放置一个 iptable 规则,将所有请求转发到端口 5432 上的 Vagrant 盒子到目的地 172.17.0.2:5432,如下所示:

iptables -t nat -A PREROUTING -p tcp --dport 5432 -j DNAT --to-destination 172.17.0.2:5432
iptables -t nat -A POSTROUTING -j MASQUERADE

但我还是做不到。感谢您的帮助!

无需在外部添加 iptables 规则。 vagrant 端口转发会自行处理。

检查以下几点:

  1. 检查 vagrant 实例中的 PostgreSQL 端口。如果端口与特定 IP 绑定,那么您必须在 Vagrantfile 中提供 IP 以转发该 IP 和端口。喜欢

guest_ip (string) - The guest IP to bind the forwarded port to. If this is not set, the port will go to every IP interface. By default, this is empty.

  1. 同样,你也可以给主机IP

host_ip (string) - The IP on the host you want to bind the forwarded port to. If not specified, it will be bound to every IP. By default, this is empty.

如果一切正常,您可以使用如下命令进行连接:

psql -p 5432 -d db_name -U user -h localhost

不要忘记添加 -h 主机名或 ip。另见这些答案:

1.unable to connect to forwarded port over ssh

2.Accessing to a remote PostgreSQL server using port forwarding to another machine