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 can I connect to a docker container using its name instead of its IP address?
  • How can i run java applications in docker using apache or tomcat server
  • Tensorflow Object Detection Killed before starting
  • How to get a list of images on docker registry v2
  • Elastic Beanstalk local environment (with Docker) connection refused
  • How to pass host ip address to docker in mac OS?
  • 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!

  • How to add $(…):$(…) in Docker Compose
  • Docker+SSH, how to transfer docker images from one host to another securely on a regular basis?
  • Adding files to standard images using docker-compose
  • Load Balance Web Applications on Windows Docker
  • How does device mapper “union” docker images
  • In docker run --ulimit cpu=10 does not work in some cases
  • 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.