I have read this thread and many other tutorials but still cannot get the connection to work.
I created two containers and they are on the same network net_a
, and the MySQL container was created using this command:
docker run -itd --name mysql_a -p 3319:3306 -e MYSQL_ROOT_PASSWORD=passwd --network net_a mysql:latest
In the other container I want to access a MySQL database db_a
using PyMySQL, and I tried this:
import pymysql.cursors
connection = pymysql.connect(
host="mysql_a",
user="root",
password="passwd",
database="db_a",
port=3319, charset="utf8")
cur = connection.cursor()
But an error araises:
--> 353 self.connect() 354 355 def enter(self):
/usr/local/lib/python3.8/dist-packages/pymysql/connections.py in connect(self, sock) 662 if DEBUG: 663 print(exc.traceback) --> 664 raise exc 665 666 # If e is neither DatabaseError or IOError, It's a bug.
OperationalError: (2003, "Can't connect to MySQL server on 'mysql_a' ([Errno 111] Connection refused)")
I thought it was because they are not on the same network, then I ping the container name mysql_a
from the other container and it shows this:
PING mysql_a (172.18.0.3) 56(84) bytes of data.
64 bytes from mysql_a.net_a (172.18.0.3): icmp_seq=1 ttl=64 time=0.078 ms
64 bytes from mysql_a.net_a (172.18.0.3): icmp_seq=2 ttl=64 time=0.068 ms
64 bytes from mysql_a.net_a (172.18.0.3): icmp_seq=3 ttl=64 time=0.061 ms
64 bytes from mysql_a.net_a (172.18.0.3): icmp_seq=4 ttl=64 time=0.061 ms
I wonder why it doesn't work? Maybe the single-host bridge networks don't work in this scenario and I should learn something about multi-host overlay networks?