4

I have a Flask Python API that connects with a MariaDB database in a Docker container and I'm connecting to the database with PyMysql.

The problem is that my server or application closes the connection after 10 minutes. I've already tried to increase the timeout time in the MariaDB configuration file and in PyMySQL, but to no avail. The errors are as follows:

Python error:

"OperationalError: (2006, "MySQL server has gone away 
(ConnectionResetError(104, 'Connection reset by peer'))")"

Database error:

"[Warning] Aborted connection 9 to db: 'db' user: 'user' host: 'ip'
(Got timeout reading communication packets)"

Would anyone know how to solve the problem?

I give below my MariaDB configuration file and my Python code.

Thank you in advance.

PS: I've already tried to use another Python package to connect to MariaDB, that is through the Flask SQLAlchemy, but the same behavior happens with the database connection, unfortunately. For that reason, I believe that the problem is not the Python code, but maybe the Docker image (maybe).

my.cnf

# 7 days = 604800s / 8 hours = 28800s 
wait_timeout = 604800
interactive_timeout = 28800

Python code:

from pymysql import connect
from pymysql.cursors import DictCursor


class MySQLConnection:

    def __init__(self, host, port, user, password, schema):       
        try:
            # Connect to the database
            self.connection = connect(host=host, port=port, 
                                      user=user, password=password, 
                                      db=schema, cursorclass=DictCursor, 
                                      connect_timeout=50)

            # create a cursor object
            self.cursor = self.connection.cursor()
            print("DB connection was successful!")
        except Exception as error:
            print("DB connection was failed! \nError: ", error)
            exit(1)
rmmariano
  • 896
  • 1
  • 18
  • 32

1 Answers1

0

https://docs.sqlalchemy.org/en/13/faq/connections.html#mysql-server-has-gone-away

Maybe you need pool_recycle, pool_pre_ping :)

Mio
  • 21
  • 3