OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")

Question:

when connecting to mysql database in Django ,I get the error.

  1. I’m sure mysql server is running.

  2. /var/run/mysqld/mysqld.sock doesn’t exist.

  3. When I run $ find / -name *.sock -type s, I only get /tmp/mysql.sock and some other irrelevant output.

  4. I added socket = /tmp/mysql.sock to /etc/my.cnf. And then restared mysql, exited django shell, and connected to mysql database. I still got the same error.

I searched a lot, but I still don’t know how to do.

Any help is greate. Thanks in advance.

Well, I just tried some ways. And it works.
I did as follows.

  1. Add socket = /tmp/mysql.sock .Restart the mysql server.
  2. ln -s /tmp/mysql.sock /var/lib/mysqld/mysqld.sock

I met an another problem today. I can’t login to mysql.
I’m newbie to mysql. So I guess mysql server and client use the same socket to communicate.
I add socket = /var/mysqld/mysqld.sock to [mysqld] [client] block in my.cnf and it wokrs.

Asked By: robert

||

Answers:

Use “127.0.0.1”, instead of “localhost”

DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.mysql',
      'NAME': 'django',
      'USER': 'root',
      'PASSWORD': '',
      'HOST': '127.0.0.1',
      'PORT': '3306',
   }
}
Answered By: Md. Ibrahim

in flask, you may use that

app=Flask(__name__)

app.config["MYSQL_HOST"]="127.0.0.1
app.config["MYSQL_USER"]="root"

Answered By: Can Okan Taşkıran

For me this worked
add OPTIONS attribute with read_default_file and give it the path of my.cnf file

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {
            'read_default_file': '/opt/lampp/etc/my.cnf',
        }
    }
}
Answered By: AkshayJ

I faced this problem when connecting MySQL with Django when using Docker.

Try 'PORT':'0.0.0.0'.

Do not use 'PORT': 'db'. This will not work if you tried to run your app outside Docker.

Answered By: Mahdy H.

You need to change your HOST from 'localhost' to '127.0.0.1' and check your django app 🙂

Answered By: Muhammadalive
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.