简体   繁体   中英

How to access host DB from Docker container?

I have PostgreSQL DB running locally and a Docker container with an application that wants to connect there.

How can I access localhost DB from inside docker?

docker run --rm -e "DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5432/my_db" --network="host" -p 4000:4000 my_image

The above doesn't seem to work. Neither this one: From inside of a Docker container, how do I connect to the localhost of the machine?

I think your problem is in param net. In the documentation talk about --network

docker run --rm -e "DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5432/my_db" --network="host" -p 4000:4000 my_image

The settings you have should work correctly, so the problem might be with the configuration of PostgreSQL. The first potential configuration setting I can think of is the bind address . By default this is set to only accept connections from localhost, but since the Docker container will have its own ip address PostgreSQL won't accept traffic from the container. Try setting it to listen_addresses(0.0.0.0) to see if this fixes your problem.

Also be careful to always use 127.0.0.1 as the address because localhost does not always work.

I will plagiarize my own answer from here :

Other answers did not work well for me. My container could not resolve host ip using host.docker.internal . There are two ways

  1. Sharing host network --net=host:

     docker run -it --net=host myimage 
  2. Using docker's ip address, which is usually 172.17.0.1 . You can check it by calling ifconfig command and grabbing inet addr of docker interface

     user@ubuntu:~$ ifconfig docker0 Link encap:Ethernet HWaddr 02:42:a4:a2:b2:f1 inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0 inet6 addr: fe80::42:a4ff:fea2:b2f1/64 Scope:Link 

Once you have this ip address, you can pass it as an argument to docker run and then to application or as I do it, map the location of jdbc.properties via volume to the directory on host machine, so you can manage the file externally.

  docker run -it -v /host_dir/docker_jdbc_config:${jetty_base}/var/config myimage

NOTE: Your database might not allow external connections. In case of postgresql, you need to edit 2 files, as described here and here :

  1. Edit postgresql.conf to listen on all addresses. By default it will point to localhost.

     listen_addresses = '*' 
  2. Edit pg_hba.conf to allow connections from all addresses. Add on the last line:

     host all all 0.0.0.0/0 md5 

IMPORTANT: Last step updating database access is not recommended for production use unless you are really sure what you are doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM