Unable to Connect Django to MySQL in Docker Using Docker-Compose
Attempting to establish a connection between Django and MySQL within a Docker environment using docker-compose can result in the following error:
django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'mariadb55\' (111 "Connection refused")')
Solution
To resolve this issue, it is crucial to ensure that the port and host specified in the Django settings file align with the actual configuration within the docker-compose.yml file.
Steps to Fix the Issue:
Set the Host to 'db' and Port to '3306' in settings.py:
Adjust the docker-compose.yml File:
Activate a Check for Open Ports:
Example docker-compose.yml File:
version: '3' services: db: image: mariadb:5.5 restart: always environment: - MYSQL_HOST=localhost - MYSQL_PORT=3306 - MYSQL_ROOT_HOST=% - MYSQL_DATABASE=test - MYSQL_USER=belter - MYSQL_PASSWORD=belter_2017 - MYSQL_ROOT_PASSWORD=123456_abc volumes: - /home/belter/mdbdata/mdb55:/var/lib/mysql ports: - "3302:3306" web: image: onlybelter/django_py35 command: /bin/sh -c "python check_db.py --service-name mysql --ip db --port 3306" volumes: - .:/djcode
Additional Tips:
By following these steps, you can establish a stable connection between Django and MySQL within a Docker environment using docker-compose.
The above is the detailed content of Here\'s a question-based title that captures the essence of the article: Why Can\'t My Django App Connect to MySQL in Docker Using Docker-Compose? Here are some other variations: * Django to MySQL. For more information, please follow other related articles on the PHP Chinese website!