I wanna connect my python script to MySQL in docker. Here is my docker-compose file:
version: '3.7'
services:
mysql:
image: mariadb:${MARIADB_VERSION:-latest}
container_name: mysql
volumes:
- ./mysql:/var/lib/mysql
environment:
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD:-password}
- MYSQL_USER=${MYSQL_USER:-root}
- MYSQL_PASSWORD=${MYSQL_PASSWORD:-password}
- MYSQL_DATABASE=${MYSQL_DATABASE:-db}
restart: always
script:
container_name: script
build: ./test_db
command: bash -c "python3 testDb.py"
environment:
- DB_NAME=db
- HOST=mysql
- DB_USER=root
- DB_PASSWORD=password
volumes:
- ./test_db:/var/www/html/script
depends_on:
- mysql
and here is my Python script file:
import pymysql
class TestDb:
def run(self):
conn = pymysql.connect(host='mysql', port=3306, database='db', user='root', password='password')
print(conn)
if __name__ == "__main__":
TestDb().run()
and here is my error:
script | Traceback (most recent call last):
script | File "/test_db/testDb.py", line 10, in <module>
script | TestDb().run()
script | File "/test_db/testDb.py", line 5, in run
script | conn = pymysql.connect(host='mysql', port=3306, database='sta_db', user='root', password='Alphashadow1381')
script | File "/usr/local/lib/python3.9/site-packages/pymysql/__init__.py", line 94, in Connect
script | return Connection(*args, **kwargs)
script | File "/usr/local/lib/python3.9/site-packages/pymysql/connections.py", line 327, in __init__
script | self.connect()
script | File "/usr/local/lib/python3.9/site-packages/pymysql/connections.py", line 619, in connect
script | raise exc
script | pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'mysql' ([Errno 111] Connection refused)")
How can I connect my Python script to MySQL in docker?
docker-compose up -d, wait 30-60 seconds, and run the same command again? In the log file you already have, are there either error messages from the database, or database startup messages after the Python error you quote?