Skip to content

Instantly share code, notes, and snippets.

@LuisErnestoZamb
Last active October 30, 2023 13:30
Show Gist options
  • Save LuisErnestoZamb/f0c60859b2056ad8f5a59ae42631abf9 to your computer and use it in GitHub Desktop.
Save LuisErnestoZamb/f0c60859b2056ad8f5a59ae42631abf9 to your computer and use it in GitHub Desktop.
How setting up mysql as localhost and using this outside docker on Mac OS (accessing localhost mysql from docker) - The missing guide

Mysql outside docker under same machine - only for developing purposes

For some circumstances we cannot use mysql inside docker by sharing volume and we need to use mysql outside docker under the same machine, the big question here is: once you use mysql as daemon on MAC OS and we need have access from docker: which is localhost? localhost inside docker or localhost on my own machine? I haven't found any documentation taking about this so far. I hope this help and forget about bridge connections, sharing volumes, link, or another crazy stuff. Enjoy!

  1. Temporally create an mysql root account that allow external connection (a root account with a password).
  2. Verify the range of mysql IP used by the container services (see the example Image1) - try to make a connection from the container.
  3. Modify your docker-compose.yml by including docker.for.mac.localhost as your mysql domain (this is the only way to connect something from the container to your localhost machine on MAC OS).
  4. Delete your mysql root account or modifying this by allowing only the docker connections (Maybe there is a better solution for this.)
update user set host='172.18.0.%' where host='%' and User='root'

or even:

update user set host='172.18.%.%' where host='%' and User='root'
  1. I believe the same procedure is applicable to postgres.
  2. Go to the top of this page and click on the Star button or write a comment on the bottom of the page.
@LuisErnestoZamb
Copy link
Author

host.docker.internal

@ducquoc
Copy link

ducquoc commented Oct 8, 2018

In MacOS and Windoze the host.docker.internal works out-of-the-box or new versions of Docker.

But in Linux, the host.docker.internal does not work ! (it's strange - Docker is internally Linux from the beginning). But you can add host given you are sure the IP Address of it (usually docker0 interface).

$ ip -4 addr show scope global dev docker0 | grep inet | awk '{print $2}' | cut -d / -f 1

172.17.0.1

If you use bridge, the default IP would work (like 192.168.1.x, not 172.17.0.x)
$ route | awk '/^default/ { print $2 }'

192.168.1.1

or
$ ip route | awk 'NR==1 {print $3}'

192.168.1.1

Then you can build a script to add docker.host.local to /etc/hosts Linux, or even using the docker run parameters --add-host

docker run --add-host host.docker.internal:172.17.0.1 --name busybox -it busybox /bin/sh

-Duc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment