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:

  • COPY and ADD not working in Dockerfile
  • Home symbol `~` not recognized in Dockerfile
  • Docker for windows: cannot access service on exposed port in windows container mode
  • how to find docker image and it's related subvolumes
  • Docker in Automation testing
  • Running impala sql script from Docker file
  • "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!

  • Is there a way to get the Docker Hub username of the current user?
  • Docker-local volume mount to the container:Connection refused
  • Find container size using python sdk
  • Cannot stop container with docker on windows
  • What is the default location for included files when building a docker image?
  • How to stop all containers when one container stops with docker-compose?
  • 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.