Access PostgreSQL running in Docker container in Vagrant

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:

  • docker: how to restart containers from files from /var/lib/docker/containers
  • How to link to additional container without restarting?
  • Heroku Permission denied: AH00072: make_sock: could not bind to address [::]:80
  • How to get Mesos Marathon Stdout from App Creation Command?
  • Docker does not run cron job files with external origin (host - windows)
  • Where to put folders for code in docker containers
  • 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!

  • Is Docker running within WSL or connecting back to Windows?
  • Cannot start container on docker compose
  • Docker image tag is not working
  • docker php, nginx is super slow with wordpress
  • Chain automated builds in the same Docker Hub repository
  • Unable to start docker service with error “Failed to start docker.service: Unit not found.”
  • One Solution collect form web for “Access PostgreSQL running in Docker container in Vagrant”

    No need to add iptables rule externally. vagrant port forwarding will take care itself.

    Check below points:

    1. check your PostgreSQL port in vagrant instance. if port is bind with particular IP then you have to give IP in Vagrantfile to forward that IP and port. Like

    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. Similarly, you can give host IP also

    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

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.