首页 > 解决方案 > 如何从docker连接到主机上的mysql?

问题描述

我的本地主机上有 mysql,我可以使用 root 登录:

[root@pocnnr1n1 etc]# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 5.5.52-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+

现在,我在这台主机上有一个 docker,其 IP 地址为“172.17.0.2”

从 docker ping 到主机没有问题:

root@eaa90c1059f2:/app/airflow/dags# ping 192.168.211.251
PING 192.168.211.251 (192.168.211.251): 56 data bytes
64 bytes from 192.168.211.251: icmp_seq=0 ttl=64 time=0.208 ms

从 docker,如果我手动运行 pymysql 来创建连接:

conn= pymysql.connect(host='192.168.211.251', port=3306, user='root',
passwd='root', db='airflow')

我有以下错误:

pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'172.17.0.2' (using password: YES)")

如果我将 IP 地址更改为“172.17.0.2”,如下所示:

conn= pymysql.connect(host='172.17.0.2', port=3306, user='root',
passwd='root', db='airflow')
I have the following error:

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '172.17.0.2' ([Errno 111] Connection denied)")

更新:my.cnf 如下:

[mysqld]
transaction-isolation = READ-COMMITTED
# Disabling symbolic-links is recommended to prevent assorted security risks;
# to do so, uncomment this line:
# symbolic-links = 0

key_buffer = 16M
key_buffer_size = 32M
max_allowed_packet = 32M
thread_stack = 256K
thread_cache_size = 64
query_cache_limit = 8M
query_cache_size = 64M
query_cache_type = 1

max_connections = 550
#expire_logs_days = 10
#max_binlog_size = 100M

#log_bin should be on a disk with enough free space. Replace '/var/lib/mysql/mysql_binary_log' with an appropriate path for your system
#and chown the specified folder to the mysql user.
log_bin=/var/lib/mysql/mysql_binary_log
#explicit_defaults_for_timestamp = 1

binlog_format = mixed

read_buffer_size = 2M
read_rnd_buffer_size = 16M
sort_buffer_size = 8M
join_buffer_size = 8M

# InnoDB settings
innodb_file_per_table = 1
innodb_flush_log_at_trx_commit  = 2
innodb_log_buffer_size = 64M
innodb_buffer_pool_size = 4G
innodb_thread_concurrency = 8
innodb_flush_method = O_DIRECT
innodb_log_file_size = 512M

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

标签: mysqldockermariadb

解决方案


这是来自mysql-doc

确保服务器未配置为忽略网络连接,或者(如果您尝试远程连接)未配置为仅在其网络接口上本地侦听。如果服务器是用 --skip-networking 启动的,它根本不会接受 TCP/IP 连接。如果服务器以 --bind-address=127.0.0.1 启动,它将仅在环回接口上本地侦听 TCP/IP 连接,并且不会接受远程连接。

当 docker 网络中的某些东西尝试连接本地主机时:它还尝试从远程访问 mysql。

找到my.cnf(通常/etc/mysql/my.cnf)注释该行bind-address=127.0.0.1


推荐阅读