Allowing Docker container to access Postgres running on localhost

I’ve got a docker container which is supposed to run a (HTTP) service.
This container should be able to connect to PostgresSQL running on the host machine (so it’s not part of the container). The container uses the host’s network settings:

docker run -e "DBHOST=localhost:5432" -e "DB=somedb" -e "AUTH=user:pw" -i -t --net="host" myservice

I’m using MacOSX, so Docker is running on a Virtualbox VM. I guess I need port forwarding to make this work. I’ve tried to configure that:

  • how to pass command line arguments to a python script running in docker
  • Dockerfile image path contains invalid charector
  • Tomcat docker-compose running web app
  • Docker does not start up
  • Should swarm loadbalancing perform healthchecks on its nodes?
  • How to create privilege (per user) in Kibana
  • VBoxManage controlvm "default" natpf1 "rule1,tcp,,5432,,5432";

    But this doesn’t work. If I start up the service, all I get is a connection refused message and the service cannot connect to Postgres.

    Postgres is running on port 5432, on the host machine. The “default” is the name of the VM created by Docker installer.

    What am I doing wrong? Please help!

  • Unable to connect to docker container to container
  • Can't connect to mongodb docker container from another container
  • Gradle clean task with bmuschko/gradle-docker-plugin
  • Postgres pg_hba.conf: ip range not working
  • How do you use docker-compose from a Gitlab Registry on DigitalOcean?
  • Running chrome inside docker container issue
  • One Solution collect form web for “Allowing Docker container to access Postgres running on localhost”

    I’ve had success with this using the --add-host flag, which adds an entry into the /etc/hosts in your container. Boot2docker and docker-machine both assign an ip you can use to hit your localhost from inside a container, so you just want to add an entry that points back to this.

    With boot2docker, where the default host ip is, you can just do docker run --add-host=my_localhost: ...

    With docker-machine, I think you’ll need to lookup your localhost’s mapped ip in Virtualbox, and then you can do the same: docker run --add-host=my_localhost:[localhost_mapped_ip_from_docker] ...

    Try setting that up and then trying to connect to your Postgres instance through my_localhost. Make sure you correctly set access and accepted inbound ip permissions in Postgres as well, as if it’s not listening on the container’s ip or, it won’t work no matter what.

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