'connect to host.docker.internal via mysql-connector fails

I am using a docker container that contains a python script that should be able to interact with the local! Mysql server. Both are running on my Linux Server (debian 11).

When i start the container on the Linux Server I use

"docker run --add-host=host.docker.internal:host-gateway [chosen.container]"

in order to allow the script to use a gateway to connect to the mysql database on the host.

unfortunately this always produces the following error code

mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'host.docker.internal:3306' (111 Connection refused)

I'm sure that the Mysql database is configured to allow internal access, as I can connect to the database via the cli or a ssh tunnel over mysql workbench.

Does anyone know how to make the communication between the container and the database work?

The script that is running in the docker container is the following;

import mysql.connector

mydb = mysql.connector.connect(host="host.docker.internal", user="root", password="xxxxxxxxx", database='xxx-analysis-db', port=3306)

c = mydb.cursor()


query = "SELECT * FROM [chosen Table];"

c.execute(query)

result = c.fetchall()

print(result)

the dockerfile contains:

FROM python:3.10

ADD main.py .

COPY requirements.txt requirements.txt

RUN pip install -r requirements.txt

CMD ["python","./main.py"]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source