I can't connect my docker app to my MySQL server. But I can connect the app to the server from my local machine.
I use MySQL version 8.0.20
app.py:
import mysql.connector
server_config = {
'user': 'my_user',
'password': 'my_password',
'host': '127.0.0.1',
'database': 'db',
'port': 3306,
}
conn = mysql.connector.connect(**server_config)
cursor = conn.cursor()
print('db has been connected')
Dockerfile (for app):
FROM python:3.10
WORKDIR /usr/app/src
COPY . ./
RUN pip install -r requirements.txt
requirements.txt:
mysql-connector-python==8.0.20
docker-compose.yml:
version: '3.8'
services:
app:
build: ./
command: sh -c "sleep 20s ; python3 ./app.py"
depends_on:
- db
db:
image: mysql:8.0.20
restart: always
environment:
MYSQL_DATABASE: 'db'
MYSQL_USER: 'my_user'
MYSQL_PASSWORD: 'my_password'
MYSQL_ROOT_PASSWORD: 'my_root_password'
ports:
- '3306:3306'
Traceback error:
Traceback (most recent call last):
File "/usr/app/src/./app.py", line 10, in <module>
conn = mysql.connector.connect(**server_config)
File "/usr/local/lib/python3.10/site-packages/mysql/connector/pooling.py", line 286, in connect
return CMySQLConnection(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/mysql/connector/connection_cext.py", line 101, in __init__
self.connect(**kwargs)
File "/usr/local/lib/python3.10/site-packages/mysql/connector/abstracts.py", line 1095, in connect
self._open_connection()
File "/usr/local/lib/python3.10/site-packages/mysql/connector/connection_cext.py", line 268, in _open_connection
raise get_mysql_exception(
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (111)
But if I run app.py from my local machine (server was running on docker, app.py was running without docker) the output is:
db has been connected
CodePudding user response:
Your host name is wrong. It should be db
.
Basically app container is trying to connect to its localhost:3306
which is not right. Db service is running on db:3306
.