1

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. sqlalchemy connect fail Therefore, I try to use mysql-client to connect, but still failed as same reason. through mysql-client

use host.docker.internal

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.

  1. run container --network=host
  2. (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)

Archi
  • 41
  • 6

1 Answers1

2

A couple things:

  1. Using mysql without -h or --host by default tries to connect to localhost via a socket file.
  2. Using mysql -h host.docker.internal -u root -p is correct. However, as the error message states, you'll need to provide permission for the root user to connect via non-localhost. If using the mysql container, run with -e MYSQL_ROOT_HOST=% or similar set.
  3. I don't know which command you're using to start the mysql container. Make sure you're publishing the ports with -p 3306:3306 to all for cross-container communication.
jcragun
  • 2,060
  • 10
  • 8