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:

  • How can I copy a directory or file to a docker image from localhost on ubuntu14.04?
  • How can I upgrade Docker on a Mac?
  • Dockerfile vim installation does not work
  • Execution of python script hangs while executing docker exec command
  • Is there any way to make Docker download public images faster?
  • Connection refused when try to connect http server in docker daemon container
  • "forwarded_port", guest: 5432, host: 5432

    But I’m guessing this is not enough since the Docker container has its own IP ( 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 like this:

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

    But I still can’t make it work. Thankful for any help!

  • Docker nginx oci runtime error: could not synchronise with container process: not a directory
  • Can't push a new docker image to bluemix
  • Execute for loop in docker container
  • Node and docker - how to handle babel or typescript build?
  • Failed to run a script using IntelliJ plugin for docker deplyment
  • Can I use restarting docker instead restarting app in container?
  • 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.