为了方便,使用python测试连接mysql容器
脚本内容非常简单
#!/usr/bin/python3 import pymysql conn=pymysql.connect(host="localhost",user="root",port=3306,password="12345",database="mydb") cursor=conn.cursor() cursor.execute("select count(*) from mydb.t") cursor.close() conn.close()
执行上述脚本后,发生以下异常
Traceback (most recent call last): File "./p.py", line 6, in <module> conn=pymysql.connect(host="localhost",user="root",port=3306,password="12345",database="mydb") File "/usr/local/lib64/python3.6/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/local/lib64/python3.6/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "/usr/local/lib64/python3.6/site-packages/pymysql/connections.py", line 598, in connect self._get_server_information() File "/usr/local/lib64/python3.6/site-packages/pymysql/connections.py", line 975, in _get_server_information packet = self._read_packet() File "/usr/local/lib64/python3.6/site-packages/pymysql/connections.py", line 657, in _read_packet packet_header = self._read_bytes(4) File "/usr/local/lib64/python3.6/site-packages/pymysql/connections.py", line 707, in _read_bytes CR.CR_SERVER_LOST, "Lost connection to MySQL server during query") pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')
从错误信息看,是不能够正常连接到OMC,刚开始怀疑是pymysql.connect方法中传递的参数不正确,但无论怎么修改,始终出现2013的异常,后来查看mysql配置文件,发现存在一条配置
bind_address=127.0.0.1
改参数限制了mysql不能被远程访问,所以在容器外部没法访问到容器内部的mysql,造成2013异常,注释掉改配置,重启mysql docker容器,访问正常
另外如果将改配置对应的ip地址改为宿主机地址,还会出现如下异常
Traceback (most recent call last): File "./p.py", line 6, in <module> conn=pymysql.connect(host="localhost",user="root",port=3306,password="12345",database="mydb") File "/usr/local/lib64/python3.6/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/local/lib64/python3.6/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "/usr/local/lib64/python3.6/site-packages/pymysql/connections.py", line 630, in connect raise exc pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
且mysql未正常启动,错误日志中有如下信息
2019-10-15T02:27:03.769286Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. 2019-10-15T02:27:03.791952Z 0 [ERROR] [MY-010262] [Server] Can't start server: Bind on TCP/IP port: Cannot assign requested address 2019-10-15T02:27:03.791960Z 0 [ERROR] [MY-010257] [Server] Do you already have another mysqld server running on port: 3306 ? 2019-10-15T02:27:03.792191Z 0 [ERROR] [MY-010119] [Server] Aborting 2019-10-15T02:27:04.855205Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.17) MySQL Community Server - GPL.