Connecting a Docker Container to a MySQL Server Running on the host

Written by James McDonald

August 29, 2018

Just been trying to connect from a Docker container to a MySQL server running on the Docker Host.

I am running Docker Community Edition 18.03.1-ce-mac65 (24312) on a Macbook Pro MacOS High Sierra version 10.13.6

What didn’t work

Found a lot of information saying to use the output of ip route command run from inside the container:

HOST_IP=`ip route | awk '/default/ {print $3}'`
# output 172.17.0.1
mysql -h $HOST_IP -u jamesm -p
Enter password:
ERROR 2003 (HY000): Can't connect to MySQL server on '172.17.0.1' (111)

But the above doesn’t work with my setup

I made sure mysqld was listening on all IP addresses because I thought it may not have bound to the docker IP

netstat -an | grep 3306
tcp4       0      0  *.3306                 *.*                    LISTEN

Although the my.conf bind-address was set to 0.0.0.0 and mysqld was listening on all IP addresses. I still couldn’t connect to the 172.17.0.1 IP

What did work

Then discovered that from within a container there is a hostname host.docker.internal that will resolve to an IP that the host will have bound the mysqld process to and suddenly all was good in the world

root@bc98cf2054b8:~# ping host.docker.internal
PING host.docker.internal (192.168.65.2): 56 data bytes
64 bytes from 192.168.65.2: icmp_seq=0 ttl=37 time=0.245 ms

root@bc98cf2054b8:~# mysql -h host.docker.internal -u jamesm -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 85
Server version: 5.7.19 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

In hind sight it should have all been obvious. As the Docker CE GUI has the host subnet setting on the Advanced tab:

The interesting thing is that the IP address that is found by resolving host.docker.internal inside the container. Does not show up when you list either the container or the hosts IP configuration

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…

Squarespace Image Export

To gain continued access to your Squarespace website images after cancelling your subscription you have several...

MySQL 8.x GRANT ALL STATEMENT

-- CREATE CREATE USER 'tgnrestoreuser'@'localhost' IDENTIFIED BY 'AppleSauceLoveBird2024'; GRANT ALL PRIVILEGES ON...

Exetel Opt-Out of CGNAT

If your port forwards and inbound and/or outbound site-to-site VPN's have failed when switching to Exetel due to their...