Mariadb error 2002 hy000

Common problems when trying to connect to MariaDB.

Contents

  1. Server Not Running in Specified Location
  2. Unable to Connect from a Remote Location
  3. Authentication Problems
    1. Problems Exporting Query Results
    2. Access to the Server, but not to a Database
    3. Option Files and Environment Variables
    4. Unable to Connect to a Running Server / Lost root Password
    5. localhost and %
  4. See Also

If you are completely new to MariaDB and relational databases, you may want to start with the MariaDB Primer. Also, make sure you understand the connection parameters discussed in the Connecting to MariaDB article.

There are a number of common problems that can occur when connecting to MariaDB.

Server Not Running in Specified Location

If the error you get is something like:

mysql -uname -p
ERROR 2002 (HY000): Can't connect to local MySQL server through 
  socket '/var/run/mysqld/mysqld.sock' (2 "No such file or directory")

or

mysql -uname -p --port=3307 --protocol=tcp
ERROR 2003 (HY000): Can't connect to MySQL server on  'localhost' 
  (111 "Connection refused")

the server is either not running, or not running on the specified port, socket or pipe. Make sure you are using the correct host, port, pipe, socket and protocol options, or alternatively, see Getting, Installing and Upgrading MariaDB, Starting and Stopping MariaDB or Troubleshooting Installation Issues.

The socket file can be in a non-standard path. In this case, the socket option is probably written in the my.cnf file. Check that its value is identical in the [mysqld] and [client] sections; if not, the client will look for a socket in a wrong place.

If unsure where the Unix socket file is running, it’s possible to find this out, for example:

netstat -ln | grep mysqld
unix  2      [ ACC ]     STREAM     LISTENING     33209505 /var/run/mysqld/mysqld.sock

Unable to Connect from a Remote Location

Usually, the MariaDB server does not by default accept connections from a remote client or connecting with tcp and a hostname and has to be configured to permit these.

(/my/maria-10.4) ./client/mysql --host=myhost --protocol=tcp --port=3306 test
ERROR 2002 (HY000): Can't connect to MySQL server on 'myhost' (115)
(/my/maria-10.4) telnet myhost 3306
Trying 192.168.0.11...
telnet: connect to address 192.168.0.11: Connection refused
(/my/maria-10.4) perror 115
OS error code 115:  Operation now in progress

To solve this, see Configuring MariaDB for Remote Client Access

Authentication Problems

Note that from MariaDB 10.4.3, the unix_socket authentication plugin is enabled by default on Unix-like systems. This uses operating system credentials when connecting to MariaDB via the local Unix socket file. See unix_socket authentication plugin for instructions on connecting and on switching to password-based authentication as well as Authentication from MariaDB 10.4 for an overview of the MariaDB 10.4 changes..

Authentication is granted to a particular username/host combination. user1'@'localhost', for example, is not the same as user1'@'166.78.144.191'. See the GRANT article for details on granting permissions.

Passwords are hashed with PASSWORD function. If you have set a password with the SET PASSWORD statement, the PASSWORD function must be used at the same time. For example, SET PASSWORD FOR 'bob'@'%.loc.gov' = PASSWORD('newpass') rather than just SET PASSWORD FOR 'bob'@'%.loc.gov' = 'newpass';

Problems Exporting Query Results

If you can run regular queries, but get an authentication error when running the SELECT … INTO OUTFILE, SELECT … INTO DUMPFILE or LOAD DATA INFILE statements, you do not have permission to write files to the server. This requires the FILE privilege. See the GRANT article.

Access to the Server, but not to a Database

If you can connect to the server, but not to a database, for example:

USE test;
ERROR 1044 (42000): Access denied for user 'ian'@'localhost' to database 'test'

or can connect to a particular database, but not another, for example
mysql -u name db1 works but not mysql -u name db2, you have not been granted permission for the particular database. See the GRANT article.

Option Files and Environment Variables

It’s possible that option files or environment variables may be providing incorrect connection parameters. Check the values provided in any option files read by the client you are using (see mysqld Configuration Files and Groups and the documentation for the particular client you’re using — see Clients and Utilities).

Option files can usually be suppressed with no-defaults option, for example:

mysqlimport --no-defaults ...

Unable to Connect to a Running Server / Lost root Password

If you are unable to connect to a server, for example because you have lost the root password, you can start the server without using the privilege tables by running the --skip-grant-tables option, which gives users full access to all tables. You can then run FLUSH PRIVILEGES to resume using the grant tables, followed by SET PASSWORD to change the password for an account.

localhost and %

You may have created a user with something like:

CREATE USER melisa identified by 'password';

This creates a user with the ‘%’ wildcard host.

select user,host from mysql.user where user='melisa';
+--------+------+
| user   | host |
+--------+------+
| melisa | %    |
+--------+------+

However, you may still be failing to login from localhost. Some setups create anonymous users, including localhost. So the following records exist in the user table:

select user,host from mysql.user where user='melisa' or user='';
+--------+-----------+
| user   | host      |
+--------+-----------+
| melisa | %         |
|        | localhost |
+--------+-----------+

Since you are connecting from localhost, the anonymous credentials, rather than those for the ‘melisa’ user, are used. The solution is either to add a new user specific to localhost, or to remove the anonymous localhost user.

See Also

  • CREATE USER
  • GRANT
  • Authentication from MariaDB 10.4
  • Authentication from MariaDB 10 4 video tutorial

If you work with MySQL then you’re probably familiar with the can’t connect to local mysql server through socket error message. And you’ll see error message like:


Error:
ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2 “No such file or directory”)

In this short article, we’ll show you how to troubleshoot and fix this issue in a jiffy.

And, don’t worry it’s a pretty straight up fix and you have nothing to worry about.

So let’s go.

  • What Is Can’t Connect to Local MySQL Server Through Socket Error?
  • How to Fix Can’t Connect to Local MySQL Server Through Socket Error
    • Solution #1: Check If MySQL Service is Runnning
    • Solution #2: Connect with 127.0.0.1
    • Solution #3: Modify the my.cnf file
    • Solution #4: Verify mysql.sock Location
    • Solution #5: Change MySQL Folder Permission
    • Solution #6: Multiple MySQL Instances
  • Conclusion on Can’t Connect to Local MySQL Server Through Socket

What Is Can’t Connect to Local MySQL Server Through Socket Error?

So what’s causing the can’t connect to local mysql server through socket error message?

This error message is basically telling you that the application is not able to locate the socket file needed to establish a MySQL connection.

And as you well know the socket file is used by the operating system to enable interface services such as MySQL or PHP to interact and communicate among each other.

For some people this appear message may occur when trying to restart MySQL and run the:

/usr/local/mysql/bin/mysql start

command resulting in the error message:

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

On the other hand, for others, this error message arises when they try to log into the MySQL database using any user credentials.

Then you have those we experience this same problem with their website application especially those built with PHP.

For example, all of a sudden the website refuses to work, and when you pry into the log file you see the error message logged there similar to this one:

SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket
  '/var/run/mysqld/mysqld.sock'

[SPECIAL OFFER]: Fast MySQL & PHP Web Hosting

[BENEFITS]:

  • FREE 1-Click Install of Open Source Apps, Blog, CMS, and much more!
  • Support for PHP, MySQL, WordPress, Drupal, Joomla and much more!
  • Multi-Domain Hosting & 99.9% Uptime Guarantee!
  • Super Fast Servers with 24/7/365 Technical Support!

Click here to access this [SPECIAL OFFER]

How to Fix Can’t Connect to Local MySQL Server Through Socket Error

So how do you fix this can’t connect to local mysql server through socket error message?

Well, here are some steps you need to take to resolving this issue:

Solution #1: Check If MySQL Service is Runnning

First of all, check to make sure the mysqld service is running or not. To check if MySQL is running, run the following command:

mysqladmin -u root -p status

And if the service is not running, then, by all means, start it up by running the following command:

service mysqld start

Once you restart the service, try again to connect to MySQL.

Solution #2: Connect with 127.0.0.1

Another possible solution to the >can’t connect to local mysql server through socket> error message is to try and connect to the MySQL using the 127.0.0.1 ip address instead of localhost.

When you use localhost to connect to MySQL, the operating system uses the socket connector.

However, if you use 127.0.0.1 ip address, the operating system will use the TCP/IP connector.

So as a possible solution when you’re having issues with the socket connector, you can try to establish the connection using TCP/IP by specifying the 127.0.0.1 ip address instead of localhost.

Solution #3: Modify the my.cnf file

The my.cnf file is a configuration file used by MySQL. And it’s processed by either the mysqld or mysqladmin service depending on the options specified.

So locate this my.cnf file which is normally in the /etc/ directory and modify it accordingly as follows:

[mysqld]

socket=/var/lib/mysql/mysql.sock 

[client]

socket=/var/lib/mysql/mysql.sock

After modifying the file restart your MySQL service and try connecting again.

Solution #4: Verify mysql.sock Location

Another possible cause of this problem is that the mysql.sock file in another directory.

So you need to locate where the mysql.sock file and create a symlink to it.

Most times the file is located in either the /data/mysql_datadir/mysql.sock or /tmp/mysql.sock

So for instance, if you locate the file in /data/mysql_datadir/mysql.sock, all you need to do is create a symlink for it using the following command:

ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock

Once you do this, go ahead and restart the MySQL service and try initiating the connection again.

[SPECIAL OFFER]: Fast MySQL & PHP Web Hosting

[BENEFITS]:

  • FREE 1-Click Install of Open Source Apps, Blog, CMS, and much more!
  • Support for PHP, MySQL, WordPress, Drupal, Joomla and much more!
  • Multi-Domain Hosting & 99.9% Uptime Guarantee!
  • Super Fast Servers with 24/7/365 Technical Support!

Click here to access this [SPECIAL OFFER]

Solution #5: Change MySQL Folder Permission

There one other possible solution fixing this issue and that is to change the MySQL folder’s permission.

And this can be done easily by running the following command if you’re working on a local environment:

sudo chmod -R 755 /var/lib/mysql/

After which you can restart mysql service:

service mysqld start

Then try to establish the connection again.

Solution #6: Multiple MySQL Instances

In some cases, the installation of multiple MySQL on the server environment causes this problem.

So you have a case whereby multiple instances of MySQL are running at the same time.

As such the issue running the following commands can fix the issue:

ps -A|grep mysql

Next, kill the mysql process by running this command:

sudo pkill mysql

Then do the same thing for mysqld:

ps -A|grep mysqld

Again, kill this process as well:

sudo pkill mysqld

Finally, go ahead run the following commands to restart and connect to the MySQL server:

sudo service mysql restart
mysql -u root -p

Conclusion on Can’t Connect to Local MySQL Server Through Socket

We hope one of the above possible solutions to the can’t connect to local mysql server through socket error resolves your situation.

[SPECIAL OFFER]: Fast MySQL & PHP Web Hosting

[BENEFITS]:

  • FREE 1-Click Install of Open Source Apps, Blog, CMS, and much more!
  • Support for PHP, MySQL, WordPress, Drupal, Joomla and much more!
  • Multi-Domain Hosting & 99.9% Uptime Guarantee!
  • Super Fast Servers with 24/7/365 Technical Support!

Click here to access this [SPECIAL OFFER]

10 апреля, 2019 12:27 пп
6 181 views
| Комментариев нет

MariaDB, mySQL

Этот мануал является частью серии статей по устранению неполадок и диагностике MySQL. Здесь мы рассмотрим некоторые общие проблемы, с которыми сталкиваются многие пользователи MySQL, и предоставим рекомендации по устранению конкретных ошибок. Также здесь вы найдете ссылки на другие мануалы и официальную документацию по MySQL, которые могут быть полезны в некоторых случаях.

Читайте также:

  • Доступ к логам ошибок MySQL
  • Устранение неполадок в запросах MySQL
  • Управление удаленным доступом к MySQL
  • Устранение сбоев в MySQL
  • Восстановление поврежденных таблиц MySQL

MySQL управляет соединениями с сервером БД через сокет-файл, это специальный файл, который облегчает связь между различными процессами. Сокет-файл сервера MySQL называется mysqld.sock, в системах Ubuntu он обычно хранится в каталоге /var/run/mysqld/. Этот файл создается сервисом MySQL автоматически.

Иногда изменения в системе или в конфигурации MySQL приводят к тому, что MySQL не может прочитать сокет-файл. Из-за этого у вас могут быть проблемы с доступом к вашим базам данных. Наиболее распространенная ошибка сокета выглядит следующим образом:

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

Она может возникнуть по нескольким причинам. Существует несколько путей ее устранения.

Одна из основных причин этой ошибки заключается в том, что сервис MySQL остановлен или не запустился с самого начала. А это означает, что сервис просто не смог создать сокет-файл. Чтобы выяснить, является ли это причиной возникновения ошибки в вашем случае, попробуйте запустить сервис через systemctl:

sudo systemctl start mysql

Затем попробуйте снова получить доступ к командной строке MySQL. Если вы все еще получаете ошибку сокета, проверьте расположение, где ваша установка MySQL ищет сокет-файл. Эта информация есть в файле mysqld.cnf:

sudo nano /etc/mysql/mysql.conf.d/mysql.cnf

Найдите параметр socket в разделе [mysqld]:

. . .
[mysqld]
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
. . .

Закройте файл. Затем убедитесь, что файл mysqld.sock существует, запустив команду ls в каталоге, где MySQL ищет этот файл:

ls -a /var/run/mysqld/

Если файл существует в этом каталоге, вы увидите его в выводе команды:

.  ..  mysqld.pid  mysqld.sock  mysqld.sock.lock

Если же файл не существует, возможно, причина в том, что MySQL пытается его создать, но не имеет для этого соответствующих прав. Вы можете передать все права на файл пользователю и группе mysql:

sudo chown mysql:mysql /var/run/mysqld/

После этого убедитесь, что у пользователя mysql есть необходимые права на каталог. Привилегии 775 подойдут в большинстве случаев:

sudo chmod -R 755 /var/run/mysqld/

Перезапустите MySQL, чтобы снова попытаться создать сокет-файл.

sudo systemctl restart mysql

Затем попробуйте получить доступ к командной строке MySQL еще раз. Если вы все еще сталкиваетесь с ошибкой сокета, вероятно, в вашем экземпляре MySQL существует более глубокая проблема. В этом случае вы должны просмотреть лог ошибок и поискать там какие-либо подсказки.

Читайте также: Устранение неполадок в MySQL

Этот мануал является частью серии статей по устранению неполадок и диагностике MySQL. Здесь мы рассмотрим некоторые общие проблемы, с которыми сталкиваются многие пользователи MySQL, и предоставим рекомендации по устранению конкретных ошибок. Также здесь вы найдете ссылки на другие мануалы и официальную документацию по MySQL, которые могут быть полезны в некоторых случаях.

Читайте также:

  • Доступ к логам ошибок MySQL
  • Устранение неполадок в запросах MySQL
  • Управление удаленным доступом к MySQL
  • Устранение сбоев в MySQL
  • Восстановление поврежденных таблиц MySQL

MySQL управляет соединениями с сервером БД через сокет-файл, это специальный файл, который облегчает связь между различными процессами. Сокет-файл сервера MySQL называется mysqld.sock, в системах Ubuntu он обычно хранится в каталоге /var/run/mysqld/. Этот файл создается сервисом MySQL автоматически.

Иногда изменения в системе или в конфигурации MySQL приводят к тому, что MySQL не может прочитать сокет-файл. Из-за этого у вас могут быть проблемы с доступом к вашим базам данных. Наиболее распространенная ошибка сокета выглядит следующим образом:

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

Она может возникнуть по нескольким причинам. Существует несколько путей ее устранения.

Одна из основных причин этой ошибки заключается в том, что сервис MySQL остановлен или не запустился с самого начала. А это означает, что сервис просто не смог создать сокет-файл. Чтобы выяснить, является ли это причиной возникновения ошибки в вашем случае, попробуйте запустить сервис через systemctl:

sudo systemctl start mysql

Затем попробуйте снова получить доступ к командной строке MySQL. Если вы все еще получаете ошибку сокета, проверьте расположение, где ваша установка MySQL ищет сокет-файл. Эта информация есть в файле mysqld.cnf:

sudo nano /etc/mysql/mysql.conf.d/mysql.cnf

Найдите параметр socket в разделе [mysqld]:

. . .
[mysqld]
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
. . .

Закройте файл. Затем убедитесь, что файл mysqld.sock существует, запустив команду ls в каталоге, где MySQL ищет этот файл:

ls -a /var/run/mysqld/

Если файл существует в этом каталоге, вы увидите его в выводе команды:

.  ..  mysqld.pid  mysqld.sock  mysqld.sock.lock

Если же файл не существует, возможно, причина в том, что MySQL пытается его создать, но не имеет для этого соответствующих прав. Вы можете передать все права на файл пользователю и группе mysql:

sudo chown mysql:mysql /var/run/mysqld/

После этого убедитесь, что у пользователя mysql есть необходимые права на каталог. Привилегии 775 подойдут в большинстве случаев:

sudo chmod -R 755 /var/run/mysqld/

Перезапустите MySQL, чтобы снова попытаться создать сокет-файл.

sudo systemctl restart mysql

Затем попробуйте получить доступ к командной строке MySQL еще раз. Если вы все еще сталкиваетесь с ошибкой сокета, вероятно, в вашем экземпляре MySQL существует более глубокая проблема. В этом случае вы должны просмотреть лог ошибок и поискать там какие-либо подсказки.

Читайте также: Устранение неполадок в MySQL

Tags: MySQL

When you try to connect to your MySQL server through the command line, you might encounter a MySQL ERROR 2002 as follows:

mysql -uroot -proot
ERROR 2002 (HY000): Can't connect to local MySQL server
through socket '/tmp/mysql.sock' (2)

The ERROR 2002 above happens when the mysql.sock socket file can’t be found in your filesystem.

This file is created when MySQL server is started and removed when you stop the server.

To fix this error, you need to see if MySQL server is already installed and running on your computer.

If you’re using Linux, you may need to install mysql-server in addition to the mysql package:

apt-get install mysql-server mysql

Once you have the server installed, run the server with the following command:

sudo service mysql start
# or
sudo /etc/init.d/mysql start

That should start the server and generate the mysql.sock file. You can try to connect to your MySQL server again now.

For macOS

If you’re using macOS and installed MySQL using Homebrew, then you need to make sure that the server is started using the following command:

brew services start mysql

Once MySQL is running, you can try to connect using the mysql command again.

For Windows

For Windows OS, you need to make sure that MySQL service is running in the Services panel.

Open the Windows Start menu and search for the Services panel to see the result below:

Then, scroll through the services list until you reach the services that start with "M" to look for MySQL services.

Usually, you have the MySQL version number attached to the service name.

The MySQL version installed on my computer is MySQL 8.0.26 so I have MySQL80 service listed as shown below:

If you have MySQL version 7, then you may have MySQL70 listed on the Services panel.

As you can see from the picture above, the status of MySQL80 service is empty, meaning that it’s not currently running.

If you see the same status, you can run the service by clicking the Start the service link on the left pane.

Now you can try to connect again to your MySQL server from the Command Line.

To conclude, the ERROR 2002 happens when your computer can’t connect to MySQL server because the socket file is missing.

The socket file is generated when MySQL server is started, so you probably need to start the server to make it work.

Depending on your operating system, there are different ways to start your MySQL server.

Good luck fixing the error! 👍

@igs00n

Everytime I execute mysql this error always pop up (
Errror 2002 (HY000): Can’t connect to local MySQL server through socket ‘/data/data/com.termux/files/usr/tmp/mysqld.sock’ (2))
I tried using the recommended solution from a github user by creating my.cnf.d directory and executing mysqld_safe_install and mysqld_safe -u root & but still the problem will repeat repeat once I close the terminal. Any work arounds?

@ghost

You haven’t started mysql server. Execute something like

and only then try mysql.

@rawagent09

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/data/data/com.termux/files/usr/tmp/mysqld.sock’ (2)
Same problem here please help

@ghost

@rawagent09 Ensure that server is running before trying to connect ;)

@tan86

You haven’t started mysql server. Execute something like

and only then try mysql.

In New Session mysqld_safe
Then try in first session mysql

@Adarsh-achu

You haven’t started mysql server. Execute something like

and only then try mysql.

but do we need to execute each time

@Adarsh-achu

@ghost

but do we need to execute each time

Before using client, you need to ensure that server is running, right? If mysqld_safe is not running, then you need to start it.

@SharakPL

@xeffyr how? I do everything by the book and it still doesn’t work ☹️ Worked once right after installation of mariadb, but after termux restarts it suddenly doesn’t work anymore. I run mysqld_safe -u root &, looks ok but then mysql returns

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/data/data/com.termux/files/usr/tmp/mysqld.sock’ (2)

Would you please create some tutorial on using mysql in Termux and maybe how to manage services since service is not available? Pleeeease 🙏🙏🙏

I haven’t used Termux for over a year and I could swear it was easier before.

@ghost

I do everything by the book

I don’t think there are right books about Termux exist somewhere. The only valid «book» is Termux Wiki.

Regarding MariaDB, read this article: https://wiki.termux.com/wiki/MariaDB. Carefully. And remember that Termux is not a normal Linux distribution. In fact, it neither a Linux distribution nor clean Android OS userspace. Commands copy-pasted from books will not work here.

@Adarsh-achu

@xeffyr how? I do everything by the book and it still doesn’t work ☹️ Worked once right after installation of mariadb, but after termux restarts it suddenly doesn’t work anymore. I run mysqld_safe -u root &, looks ok but then mysql returns

ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/data/data/com.termux/files/usr/tmp/mysqld.sock’ (2)

Would you please create some tutorial on using mysql in Termux and maybe how to manage services since service is not available? Pleeeease 🙏🙏🙏

I haven’t used Termux for over a year and I could swear it was easier before.

**Bro what do you need
**

@SharakPL

@Adarsh-achu nevermind ;) I think I’ve figured out sane way to manage mysql:

  1. pkg install mariadb
  2. added couple aliases to .zshrc:
alias sqlstart="mysqld_safe -u root &"
alias sqlstop="mysqladmin shutdown"
  1. sqlstart to start the server, mysql to use it, sqlstop to stop it

Sometimes, for no apparent reason, I get this Can’t connect… error on running mysql, but sqlstop and sqlstart helps (life is so much easier when you actually know what to do 😂)

I’ve also managed to configure my server properly for utf8mb4 support:

  1. pkg install mlocate and then updatedb for faster search
  2. locate 'my.cnf' and changed this one …/files/usr/etc/my.cnf so it now looks like this:
#
# This group is read both by the client and the server
# use it for options that affect everything
#

[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4

[mysqld]
collation-server = utf8mb4_unicode_ci
init-connect='SET NAMES utf8mb4'
character-set-server = utf8mb4

#
# include *.cnf from the config directory
#
!includedir /data/data/com.termux/files/usr/etc/my.cnf.d

@Kuduxaaa

First you kill mysqld process to re run mysqld

@termux
termux

locked and limited conversation to collaborators

Oct 9, 2021

Понравилась статья? Поделить с друзьями:
  • Mariadb error 1236
  • Mariadb error 1064 42000
  • Mariadb error 1045 28000 access denied for user root localhost using password yes
  • Mari license error
  • Margin of error статистика