I want to connect to host mysql in container, and I have tried some methods but none of them work.
Container: python & mysql client
Host: mysql service
Host mysql setting:
sudo apt install -y mysql-server
apt install -y default-libmysqlclient-dev
# And modify bind address: /etc/mysql/mysql.conf.d/mysqld.cnf
# bind-address = 0.0.0.0
Docker container run command's setting:
RUN apt-get update &&\
apt install -y default-mysql-client &&\
apt-get install -y gcc &&\
apt-get install -y default-libmysqlclient-dev &&\
/usr/local/bin/python -m pip install --upgrade pip &&\
pip install --no-cache-dir SQLAlchemy
My python file in container:
from sqlalchemy import create_engine
from sqlalchemy import text
SQLALCHEMY_DATABASE_URI = "mysql://root:pwd@localhost:3306/mysql?charset=utf8mb4"
engine = create_engine(SQLALCHEMY_DATABASE_URI, encoding='utf8', pool_pre_ping=True) # for mysql
with engine.connect() as connection:
result = connection.execute(text("show tables;"))
print(result.all())
Envrionment: Ubuntu: 20.04 Docker version: 20.10 Mysql version: 8.0
My purpose is to connect to mysql throught sqlalchemy in container, but not even through mysql-client.
Therefore, I try to use mysql-client to connect, but still failed as same reason.
I have tried several method:
- allow bind-address
- run container with: --add-host host.docker.internal:host-gateway
- without --add-host, try IP address
Most of the solution just say add --add-host host.docker.internal:host-gateway and it can work, But not work for me.
Does anyone solve this problem? Thanks!
Update:
I have tried a method that works.
- run container --network=host
- (in container)# mysql -h 127.0.0.1 -u root ...
But I don't want to use --network=host, how can I connect to host mysql with "host.docker.internal"?
Update:
Problem solved. I run container with --add-host host.docker.internal:host-gateway
connect to db with: mysql -h host.docker.internal
And in mysql, update mysql.user root's host to '%'.
(allow non-localhost connect)