How can I connect my WSL docker container to a local instance of Mariadb/MySql on Windows?

Solution 1:

Instead of installing Docker within Ubuntu within WSL 2, you probably will have better results installing Docker Desktop directly on Windows. It still uses WSL 2 to run your containers, but it integrates better with Windows.

Specifically, Docker Desktop adds a hostname to the internal DNS resolver named host.docker.internal that resolves to the host computer.


You can probably also do this without Docker Desktop, but it is pretty annoying since it needs to be done again every time you start a container and the information changes when you reboot. Here is what you would have to do (I have not actually tested this, but in theory it should work):

  1. Make sure you are using Docker 20.04 or newer.
  2. In your Ubuntu instance, determine the internal IP address of Windows - run route -n and find the "Gateway" address. Note that this address may change when you reboot your computer.
  3. Start your Docker containers with the following two additional arguments: --add-host=host.docker.internal:<THE_GATEWAY_IP_ADDRESS_YOU_FOUND_BEFORE> --net=host. This will give your container the ability to use host.docker.internal to connect to Windows services.

(Note that you cannot use --add-host=host.docker.internal:host-gateway as printed in many tutorials because that will point to Ubuntu in WSL, not to Windows.)