Connect to MySQL on localhost from Docker container

Even if you configure MySQL to listen on all interfaces, and then from your container access MySQL from a non-loopback IP, you may find that Docker’s routing, NAT, and firewall rules do not allow you to access services running on the host. The fast workaround for this is to run your container on the host network stack with:

docker run -tid -v $(pwd):/code -p 3306:3306 -p 5000:5000 \
  --name container --net host container

You can also also move MySQL inside a container running on the same Docker network, and then access it via the container name using Docker’s DNS service discovery.


Use the default route. For example:

~# ip route show | grep "default" | awk '{print $3}'
172.18.0.1

then

mysql -h 172.18.0.1 -P 3306 -u root -p

if you need to automate that, let's say, use that IP on a shell script, send it to a shell script, take it as:

host=$(ip route show | grep \"default\" | awk '{print $3}' | xargs echo -n)

then you have the host ip addr on $host

Tags:

Docker

Mysql