简体   繁体   中英

Django/Docker-compose: Retry Database Connection when: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")

This question have been asked here: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") and the answer has been to wait for the database to be ready.

However, the official documentation here: https://docs.docker.com/compose/startup-order/ suggests that instead an in app retry method is implemented in order to retry the database connection when this fails.

To handle this, design your application to attempt to re-establish a connection to the database after a failure. If the application retries the connection, it can eventually connect to the database.

The best solution is to perform this check in your application code, both at startup and whenever a connection is lost for any reason.

Unfortunately, the documentation just ends there and does not provide any examples or guides on how to implement this retry method. Does anyone knows how to do that in a clean way?

Restart django cassandra conection in manage.py

   #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import logging
import os
import sys
from time import sleep

from cassandra.cluster import NoHostAvailable
from django.core.management import execute_from_command_line

MAX_RETRIES_NUM = 10

def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')
    try:
        from django.core.management.commands.runserver import Command
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    from django.db import connections
    conn = connections['default']
    no_host_available = True
    retry_count = 0
    sleep_time = 1

    while no_host_available:
        try:
            conn.connect()
        except NoHostAvailable:
            if retry_count == MAX_RETRIES_NUM:
                sys.exit()
            logging.warning(f'Error de conexión con la base de datos. Reintentando conexión en {sleep_time}s')
            sleep(sleep_time)
        else:
            no_host_available = False

        sleep_time *= 1.5
        retry_count += 1

    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM