Best way to connect a docker container to a locally installed MySQL DB?

I have a docker container running with one port mapping open currently (mapping container port 80 to 10000 for external access), and I’m attempting to also open the MySQL port so a locally installed database on the machine running the container can link to the docker container. However, despite all I’ve read and researched, I simply cannot figure out how to do it.

If it matters, I’m working with a raspberry pi 5. I’ve tried doing -p 3306:3306 (pi throws an error since 3306 is open locally already) and setting the network mode to host (which breaks my port forward of 10000:80 and makes the container’s software inaccessible).

How would I best solve this issue?

1 Like

Your database is inside a Docker container?

If not, run hostname -I, usually you can use the first IP to connect to services on the host.

Best practice is to create a Docker network, attach all containers (proxy, DB, app) to it.

The database is on the Pi outside the container.

Yeah, I was thinking about creating a docker container running Budibase, MySQL, and PHPMyAdmin and doing all of the specific project-related stuff inside the docker container. I would love to know how I can let the docker container see MySQL locally, but if doing it all inside the container would be quicker or more efficient, I can pick that route.

All I care about is making sure whatever end result can be backed up. I’d hate for a power surge or something to fry the Pi and destroy all the progress.

Hi

To answer to your last point : you can have Mysql running in a container and, using a volume, store the database on your host. Doing this, it’s just files you can put in your backup strategy.

On my own, I don’t use anymore (exception for production) services like Mysql, postgresql,… outside Docker. It’s soooo great to be able to start any services, stop, upgrade versions, change exposedvport number,… thanks to Docker.

from inside of the Docker container.

Best practice is to have everything in separate Docker containers, then access each other by service or container name.

There are hundreds of tutorials available, so I will not write another one here :wink:

Since port 3306 is already in use on your host, you should map MySQL to a different external port. Try:

-p 3307:3306

Then, connect using localhost:3307.

Alternatively, use Docker networks to link your container directly to the host’s MySQL without exposing ports:

docker network create my_network
docker network connect my_network my_container

Then, in your container, connect to MySQL using host.docker.internal (or 172.17.0.1 if that doesn’t work).

Avoid --network host if you need multiple port mappings.

Why create a Docker network to connect to a service running directly on host?

host.docker.internal is available in Docker Desktop, not automatically in Docker CE.

And a database on host is not necessarily listening on the Docker gateway IP.

1 Like