Home  >  Article  >  Database  >  How to Fix \"OperationalError: Can\'t connect to MySQL server\" When Using Django and Docker?

How to Fix \"OperationalError: Can\'t connect to MySQL server\" When Using Django and Docker?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 19:35:30512browse

How to Fix

Connecting Django to MySQL in Docker

When attempting to connect Django to MySQL in a Docker environment using Compose, you may encounter an "OperationalError: Can't connect to MySQL server" issue. This error typically arises due to incorrect container configurations or database settings.

Resolving the Issue

The correct parameters to establish a connection between Django and MySQL in Docker are:

  • Set 'HOST': 'db' in Django's settings.py file.
  • Use 3306 as the port number in settings.py.
  • Set the MYSQL_PORT environment variable to 3306 in docker-compose.yml.
  • Keep the MYSQL_HOST environment variable as localhost.

To ensure that you're connected successfully, you can use the following command in your docker-compose.yml file:

  web:
    image: onlybelter/django_py35
    command: /bin/sh -c "python check_db.py --service-name mysql --ip db --port 3306"
    volumes:
      - .:/djcode

This command runs a script that checks if the MySQL port is open. If it is, the script will display a message indicating success.

Additional Tips

  • To connect to the MySQL container directly, use mysql -h 127.0.0.1 -P 3302 -u root -p in your shell.
  • If you have multiple Django containers running, make sure to use different port numbers for each one to avoid conflicts.
  • You can use Docker's docker-compose logs command to check for any potential errors or warnings related to database connectivity.

The above is the detailed content of How to Fix \"OperationalError: Can\'t connect to MySQL server\" When Using Django and Docker?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn