If I have a mysql database running on some host machine, and that host is also running a docker container: How would I access the mysql database from within the docker container that is running on the host?.
For instance, is there a way to publish a hosts port to the container (the inverse of what docker run -p does)?
This question is related to
docker
From Docker 17.06 onwards, a special Mac-only DNS name is available in docker containers that resolves to the IP address of the host. It is:
docker.for.mac.localhost
The documentation is here: https://docs.docker.com/docker-for-mac/networking/#httphttps-proxy-support
If you want access to a Docker container where there is a DB, you have to add a bash:
docker exec -it postgresql bash
postgresql is the container name.
Once inside, from the bash, access to DB e.g:
$psql -U postgres
Other answers did not work well for me. My container could not resolve host ip using host.docker.internal. There are two ways
Sharing host network --net=host:
docker run -it --net=host myimage
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:
Edit postgresql.conf to listen on all addresses. By default it will point to localhost.
listen_addresses = '*'
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.
Use host.docker.internal from Docker 18.03 onwards.
From the 18.03 docs:
I want to connect from a container to a service on the host
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name
host.docker.internal
, which resolves to the internal IP address used by the host.The gateway is also reachable as
gateway.docker.internal
.
EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:
mysql://host.docker.internal:3306/my_awesome_database
Source: Stackoverflow.com