I have a Vagrant box in which I have a Docker container that runs PostgreSQL. The container is the official one found here
I want to be able to connect to Postgres from the host (i.e outside of Vagrant) using psql but can't get it to work. (Get a "could not connect"-error). I have added a port forward in my Vagrantfile:
config.vm.network "forwarded_port", guest: 5432, host: 5432
But I'm guessing this is not enough since the Docker container has its own IP (172.17.0.2)? My thought was that I would put a iptable rule on the box that forwards all requests to the Vagrant box on port 5432 to destination 172.17.0.2:5432 like this:
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
But I still can't make it work. Thankful for any help!
No need to add iptables
rule externally. vagrant port forwarding will take care itself.
Check below points:
Vagrantfile
to forward that IP and port. Likeguest_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.
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.
If everything ok and you can connect using command like:
psql -p 5432 -d db_name -U user -h localhost
Don't forget to add -h
with hostname or ip. Also see These answer:
1.unable to connect to forwarded port over ssh
2.Accessing to a remote PostgreSQL server using port forwarding to another machine