简体   繁体   中英

Django unable to connect to MySQL server

I have a Django version (1.10) which is installed on my MacBookPro (El Capitan OS X) and I would like to connect the API to my MySQL Database which is located on a distant server (Ubuntu - same network as my job network).

I get this error when I'm running the Django server :

django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.30.10.58' (61)")

This is my settings.py file from my project :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Etat_Civil',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '172.30.10.58',
        'PORT': '3306',
    }
}

On my Mac I installed mysqlclient / mysql connector/python

I don't work with a virtual environment because I just have one project in my laptop. So it's not necessary to isolate Python.

I think that's maybe a permission problem but I don't really know How configure that. I found some tutorials but I get problems each time.

Do you have some ideas ?

Thank you so much ;)

Looks like MySQL is configured to listen only on localhost.

You can test this by running telnet 172.30.10.59 3306 from your client machine.

Please try to follow Configuration step described here :

Edit the /etc/mysql/my.cnf file to configure MySQL to listen for connections from network hosts, change the bind-address directive to the server's IP address. For example Replace 172.30.10.59 with the appropriate address. If there are no such entry - uncomment it or create new line.

 bind-address = 172.30.10.59

Then restart mysqld with this command:

 sudo service mysql restart

Then test with telnet or by running your application once again. Also netstat would have second entry for mysqld.

Firstly, you need to allow remote connections by editing my.cnf file and commenting the line that starts with bind-address as follows (You may also just change 127.0.0.1 by your machine ip address):

#bind-address                   = 127.0.0.1

Then restart mysql service:

sudo service mysql restart

Grant privileges to your user as follows:

mysql> CREATE USER 'root'@'172.30.10.%' IDENTIFIED BY 'password';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'172.30.10.%'

To grant privileges only on Etat_Civil , you can try:

mysql> GRANT ALL PRIVILEGES ON Etat_Civil.* TO 'root'@'172.30.10.%'

The problem may be 'HOST': '172.30.10.58' You can change IP address to your hostname.

  1. If you are using Ubuntu, check the name in sudo vi /etc/hostname and sudo vi /etc/hosts
  2. If you are using docker, go to docker

    docker exec -it CONTAINER_ID bash

    sudo vi /etc/hostname and sudo vi /etc/hosts

Hope this help !

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