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:

  • Unable to access jarfile - Docker on Elastic Beanstalk
  • node-serialport failing on alpine linux
  • ElasticSearch on Elastic Beanstalk
  • How to run a Docker image from a Java program?
  • Is it safe to extract the root filesystem of a Docker.io image and use it in a chroot?
  • Application has different appearance when running through docker
  • 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!

  • Changing docker image hierarchy
  • Restarting process with pid 1 in docker swarm container (replica)
  • Can't get an interactive Docker shell inside screen
  • Can docker containers be run on live web servers?
  • Why can't I `docker exec` after installing the official Django docker image?
  • Where is the base docker image specified in Play Framework?
  • 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.