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 list the published container images in the Google Container Registry using gcloud or another CLI
  • Docker networking: how to show connected containers names
  • Docker Cloud Automated builds
  • Accessing mounted volumes from apache indocker
  • Redis Docker connection refused
  • docker run <IMAGE> <MULTIPLE COMMANDS>
  • 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!

  • do docker container IPs change on restart?
  • Reference Zeppelin to Spark Master (in Docker Container)
  • Unable to ssh localhost within a running Docker container
  • Current Base Device UUID: does not match with stored UUID:
  • How is “lxd” different from lxc/docker?
  • What are the disadvantages of a Docker container using the host network?
  • 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 192.168.59.3, you can just do docker run --add-host=my_localhost:192.168.59.3 ...

    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 0.0.0.0, 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.