For my university data base project we must create a python application with mysql-connector-python and docker.
We had made a docker-compose for MySQL that was working well with application. Due to a lack of comprehension the python app moved from a container to the local terminal. From that point the python app did no more connect to SQL container.
docker-compose.yml
version: "3.9"
services:
mysql:
restart: always
container_name: "mysql"
image: mysql:latest
ports:
- 3306:3306
expose:
- 3306
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_DATABASE=mysql
- MYSQL_USER=user
- MYSQL_PASSWORD=password
python main.py script:
# pip install -r requirements.txt
# # in requerements.txt
# # line1: mysql-connector-python
# # line2:
import mysql.connector as mysql
def main():
cnx = mysql.connect(
user='user',
password='password',
database='mysql',
host='127.0.0.1',
port=3306
)
cursor = cnx.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS test(id INTEGER(64) PRIMARY KEY, name VARCHAR(255))")
cursor.execute("INSERT INTO test VALUES (2, 'bla')")
cursor.execute("INSERT INTO test VALUES (3, 'blabla')")
cursor.execute("INSERT INTO test VALUES (4, 'blablabla')")
cursor.execute("SELECT * FROM test")
for row in cursor.fetchall():
print(row)
cursor.close()
cnx.close()
if __name__ == "__main__":
main()
First I start the docker container with the following command:
$ docker-compose down
$ docker-compose build
$ docker-compose up
I wait until the container start and start the python app with:
$ python main.py
In another terminal.
The error that append is the following one: _mysql_connector.MySQLInterfaceError: Unknown MySQL server host 'mysql' (11001)
The exception is handling but never end to process.
Personnal issue:
Python: 3.11.1
Windows: 11
Docker: 20.10.17
In order to fix that host server error, I search in followed documentation:
And check the tag mysql-connector-python on Stack Overflow.
Does someone can help me to find what did I miss ?
I deleted the 'expose' attribute in docker compose to fix it
After update:
version: "3.9"
services:
mysql:
restart: always
container_name: "mysql"
image: mysql:latest
ports:
- 3306:3306
environment:
- MYSQL_ROOT_PASSWORD=password
- MYSQL_DATABASE=mysql
- MYSQL_USER=user
- MYSQL_PASSWORD=password