Home >Database >Mysql Tutorial >Why is my Django app in Docker Compose unable to connect to MySQL, even though I have the correct port and container name?

Why is my Django app in Docker Compose unable to connect to MySQL, even though I have the correct port and container name?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 02:10:29982browse

Why is my Django app in Docker Compose unable to connect to MySQL, even though I have the correct port and container name?

Troubleshooting Failed Django-MySQL Connection in Docker Compose

In this article, we will address the issue of establishing a connection between Django and MySQL within Docker containers using Docker Compose. Despite configuring the containers as outlined in the question, the user encounters the following error:

django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL
  server on \'mariadb55\' (111 "Connection refused")')

After exhaustive troubleshooting, the user discovered the root cause and solution. Here are the crucial insights:

Key Points:

  • Verify Port Consistency: Ensure that the port number specified in the Django settings file matches the port number exposed by the MySQL container. In this case, the port should be 3306, not 3302.
  • Use Container Name for HOST: Instead of using the container's IP address, specify the container name as the HOST value in Django's database configuration.

Updated Docker Compose Config:

services:
  db:
    ...
    ports:
      - "3302:3306"
  web:
    ...
    command: python3 manage.py runserver 0.0.0.0:6001
    ...
    volumes:
      - .:/djcode
    ports:
      - "6001:6001"
    depends_on:
      - db

Updated Django Settings File:

DATABASES = {
    'default': {
        ...
        'HOST': 'db',
        'PORT': '3306',
        ...
    }
}

Additional Tips:

  • Utilize the check_db.py script to verify that the MySQL port is open before running Django.
  • Refer to the provided Dockerfile for building the Django-Py35 image.
  • Explore further details on the user's GitHub repository for additional insights.

By implementing these changes, the user successfully established the connection between Django and MySQL in Docker containers, resolving the "Can't connect to MySQL server" error.

The above is the detailed content of Why is my Django app in Docker Compose unable to connect to MySQL, even though I have the correct port and container name?. 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