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

71๐Ÿ‘

โœ…

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',
   }
}
๐Ÿ‘คMd. Ibrahim

1๐Ÿ‘

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',
        }
    }
}
๐Ÿ‘คAkshayJ

1๐Ÿ‘

You need to change your HOST from 'localhost' to '127.0.0.1' and check your django app ๐Ÿ™‚

๐Ÿ‘คMuhammadalive

0๐Ÿ‘

in flask, you may use that

app=Flask(__name__)

app.config["MYSQL_HOST"]="127.0.0.1
app.config["MYSQL_USER"]="root"โ€ฆ

0๐Ÿ‘

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.

๐Ÿ‘คMahdy H.

Leave a comment