1

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?

Lerner Zhang
  • 6,184
  • 2
  • 49
  • 66

1 Answers1

0

I add this question and answer just for those who may have made the same mistake as me. I spent three nights figuring it out. If you have published the 3306 to services outside of Docker by mapping 3306 to a certain port N on the host's interface, you should not use port N, and the 3306 should be just Ok since two containers are in the same host and network(by setting the --network arg).

The host can be configured as the container name or its IP. And here is a case in Python scenario using PyMySQL:

import pymysql.cursors
connection = pymysql.connect(
    host="mysql_a", # or 172.18.0.3 in this case
    user="root",
    password="passwd",
    database="db_a",
    port=3306, charset="utf8")
cur = connection.cursor()
  

As the doc reads:

To make a port available to services outside of Docker, or to Docker containers which are not connected to the container’s network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host to the outside world.

Lerner Zhang
  • 6,184
  • 2
  • 49
  • 66