Mysql ошибка 2002

Статья расскажет, как определять проблемы и ошибки на сервере баз данных MySQL. Вы научитесь определять причины проблем и устранять их.

MySQL — система управления базами данных (СУБД) с открытым исходным кодом от компании Oracle. Она была разработана и оптимизирована специально для работы веб-приложений. MySQL является неотъемлемой частью таких веб-сервисов, как Facebook, Twitter, Wikipedia, YouTube и многих других.

Эта статья расскажет, как определять, с чем связаны частые ошибки на сервере MySQL, и устранять их.

Не удаётся подключиться к локальному серверу

Одной из распространённых ошибок подключения клиента к серверу является «ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)».

Эта ошибка означает, что на хосте не запущен сервер MySQL (mysqld) или вы указали неправильное имя файла сокета Unix или порт TCP/IP при попытке подключения.

Убедитесь, что сервер работает. Проверьте процесс с именем mysqld на хосте сервера, используя команды ps или grep, как показано ниже.

$ ps xa | grep mysqld | grep -v mysqld

Если эти команды не показывают выходных данных, то сервер БД не работает. Поэтому клиент не может подключиться к нему. Чтобы запустить сервер, выполните команду systemctl.

$ sudo systemctl start mysql        #Debian/Ubuntu
$ sudo systemctl start mysqld       #RHEL/CentOS/Fedora

Чтобы проверить состояние службы MySQL, используйте следующую команду:

$ sudo systemctl status mysql       #Debian/Ubuntu
$ sudo systemctl status mysqld      #RHEL/CentOS/Fedora

Если в результате выполнения команды произошла ошибка службы MySQL, вы можете попробовать перезапустить службу и ещё раз проверить её состояние.

$ sudo systemctl restart mysql
$ sudo systemctl status mysql

Если сервер работает (как показано) и вы по-прежнему видите эту ошибку, вам следует проверить, не заблокирован ли порт TCP/IP брандмауэром или любой другой службой блокировки портов.

Для поиска порта, который прослушивается сервером, используйте команду netstat.

$ sudo netstat -tlpn | grep "mysql"

Ещё одна похожая и часто встречающаяся ошибка подключения — «(2003) Can’t connect to MySQL server on ‘server’ (10061)». Это означает, что в сетевом соединении было отказано.

Следует проверить, работает ли в системе сервер MySQL (смотрите выше) и на тот ли порт вы подключаетесь (как найти порт, можно посмотреть выше).

Похожие частые ошибки, с которыми вы можете столкнуться при попытке подключиться к серверу MySQL:

ERROR 2003: Cannot connect to MySQL server on 'host_name' (111)
ERROR 2002: Cannot connect to local MySQL server through socket '/tmp/mysql.sock' (111)

Ошибки запрета доступа в MySQL

В MySQL учётная запись (УЗ) определяется именем пользователя и клиентским хостом, с которого пользователь может подключиться. УЗ может также иметь данные для аутентификации (например, пароль).

Причин для запрета доступа может быть много. Одна из них связана с учётными записями MySQL, которые сервер разрешает использовать клиентским программам при подключении. Это означает, что имя пользователя, указанное в соединении, может не иметь прав доступа к базе данных.

В MySQL есть возможность создавать учётные записи, позволяющие пользователям клиентских программ подключаться к серверу и получать доступ к данным. Поэтому при ошибке доступа проверьте разрешение УЗ на подключение к серверу через клиентскую программу.

Увидеть разрешённые привилегии учётной записи можно, выполнив в консоли команду SHOW GRANTS
Входим в консоль (пример для Unix, для Windows консоль можно найти в стартовом меню):

В консоли вводим команду:

> SHOW GRANTS FOR 'tecmint'@'localhost';

Дать привилегии конкретному пользователю в БД по IP-адресу можно, используя следующие команды:

> grant all privileges on *.test_db to 'tecmint'@'192.168.0.100';
> flush privileges;

Ошибки запрещённого доступа могут также возникнуть из-за проблем с подключением к MySQL (см. выше).

Потеря соединения с сервером MySQL

С этой ошибкой можно столкнуться по одной из следующих причин:

  • плохое сетевое соединение;
  • истекло время ожидания соединения;
  • размер BLOB  больше, чем max_allowed_packet.

В первом случае убедитесь, что у вас стабильное сетевое подключение (особенно, если подключаетесь удалённо).

Если проблема с тайм-аутом соединения (особенно при первоначальном соединении MySQL с сервером), увеличьте значение параметра connect_timeout.

В случае с размером BLOB нужно установить более высокое значение для max_allowed_packet в файле конфигурации /etc/my.cnf в разделах [mysqld] или [client] как показано ниже.

[mysqld]
connect_timeout=100
max_allowed_packet=500M

Если файл конфигурации недоступен, это значение можно установить с помощью следующей команды.

> SET GLOBAL connect_timeout=100;
> SET GLOBAL max_allowed_packet=524288000;

Слишком много подключений

Эта ошибка означает, что все доступные соединения используются клиентскими программами. Количество соединений (по умолчанию 151) контролируется системной переменной max_connections. Устранить проблему можно, увеличив значение переменной в файле конфигурации /etc/my.cnf.

[mysqld]
max_connections=1000

Недостаточно памяти

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

Сначала нужно убедиться, что запрос правильный. Если это так, то нужно выполнить одно из следующих действий:

  • если клиент MySQL используется напрямую, запустите его с ключом --quick switch, чтобы отключить кешированные результаты;
  • если вы используете драйвер MyODBC, пользовательский интерфейс (UI) имеет расширенную вкладку с опциями. Отметьте галочкой «Do not cache result» (не кешировать результат).

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

$ sudo apt-get install mysqltuner     #Debian/Ubuntu
$ sudo yum install mysqltuner         #RHEL/CentOS/Fedora
$ mysqltuner

MySQL продолжает «падать»

Если такая проблема возникает, необходимо выяснить, заключается она в сервере или в клиенте. Обратите внимание, что многие сбои сервера вызваны повреждёнными файлами данных или индексными файлами.

Вы можете проверить состояние сервера, чтобы определить, как долго он работал.

$ sudo systemctl status mysql       #Debian/Ubuntu
$ sudo systemctl status mysqld      #RHEL/CentOS/Fedora

Чтобы узнать время безотказной работы сервера, запустите команду mysqladmin.

$ sudo mysqladmin version -p 

Кроме того, можно остановить сервер, сделать отладку MySQL и снова запустить службу. Для отображения статистики процессов MySQL во время выполнения других процессов откройте окно командной строки и введите следующее:

$ sudo mysqladmin -i 5 status

Или

$ sudo mysqladmin -i 5 -r status

Заключение

Самое важное при диагностике — понять, что именно вызвало ошибку. Следующие шаги помогут вам в этом:

  • Первый и самый важный шаг — просмотреть журналы MySQL, которые хранятся в каталоге /var/log/mysql/. Вы можете использовать утилиты командной строки вроде tail для чтения файлов журнала.
  • Если служба MySQL не запускается, проверьте её состояние с помощью systemctl. Или используйте команду journalctl (с флагом -xe) в systemd.
  • Вы также можете проверить файл системного журнала (например, /var/log/messages) на предмет обнаружения ошибок.
  • Попробуйте использовать такие инструменты, как Mytop, glances, top, ps или htop, чтобы проверить, какая программа использует весь ресурс процессора или блокирует машину. Они также помогут определить нехватку памяти, дискового пространства, файловых дескрипторов или какого-либо другого важного ресурса.
  • Если проблема в каком-либо процессе, можно попытаться его принудительно остановить, а затем запустить (при необходимости).
  • Если вы уверены, что проблемы именно на стороне сервера, можете выполнить команды: mysqladmin -u root ping или mysqladmin -u root processlist, чтобы получить от него ответ.
  • Если при подключении проблема не связана с сервером, проверьте, нормально ли работает клиент. Попробуйте получить какие-либо его выходные данные для устранения неполадок.

Перевод статьи «Useful Tips to Troubleshoot Common Errors in 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! 👍

Databases play a critical role in the proper working of any web applications. They store, organize and manage a large amount of user data.

Any problem with database connectivity can cause website errors. And the error show up as “sqlstate hy000 error 2002.”

At Bobcares, we specialize in fixing database errors for our customers as part of our Server Management Services.

Today, we’ll see various reasons for sqlstate hy000 error 2002 and how our Database Engineers fix it.

Examining sqlstate 2002 error

Before we dive into the solution, let’s first check the sqlstate 2002 error in detail.

In general, when we configure any PHP application, we specify the details of the database in the configuration file. The same is applicable in case of popular content management systems like WordPress, Joomla, Magento, etc. And, when we update or change any setting in the website, it gets saved on the database. For this to work, there should not be any problem with database connection with MySQL host server.

The database connection can fail due to reasons like wrong database details in the configuration file, port restrictions on the server, missing files, lack of resources on the server and so on.

In simple terms, MySQL error 2002 denotes a problem of connection between the website code and the database.

There are many variants of the sqlstate hy000 2002 error. The details are readily available in the second part of the error message.

From our experience in managing servers, our Dedicated Engineers see variants of sqlstate hy000 error 2002 as

Connection failed: SQLSTATE[HY000] [2002] Connection refused
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
SQLSTATE[HY000] [2002] Resource temporarily unavailable
exit status 3

Again, a similar error on a Magento website appear as :

What causes sqlstate hy000 error 2002?

Now, let’s have a look on the possible causes for sqlstate hy000 error 2002.

1.MySQL server not running

In many of the cases where websites report sqlstate 2002 error, the underlying reason would be stopped MySQL server. And, this can happen due to broken MySQL libraries, resource crunch on the server, etc. When MySQL is not running on the server, the website will not be able to connect to the database and its reports “Connection refused error.

2. Incorrect database settings

Similarly, a major reason for sqlstate hy000 2002 error is the incorrect database settings in the configuration file. For the proper working of the program, the file should contain correct database server name, database user details and password.

If the MySQL service is listening on 127.0.0.1, the same settings should be given in the database connection string. Moreover, the MySQL server should accept connections on this IP address too.

3. Insufficient server resources

Last and not the least, insufficient server resources also can be a reason for MySQL errors. When the server has too many MySQL queries, it requires too much server memory. Additionally, when websites use resource intensive queries, it add to the server load and lack of memory on the server. It ends up in errors like “SQLSTATE[HY000] [2002] Resource temporarily unavailable.

How we fix sqlstate hy000 error 2002

Let’s take a look on how our Dedicated Engineers helped one of our customers to fix the sqlstate hy000 error 2002.

The customer was using a PHP tracking script on his website. There was a high volume of MySQL activity (about 4 inserts a second), from this tracking script, and this was causing the MySQL Connection time out error. And, on the website it resulted in error:

Exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Connection timed out

It was a sign of PHP script timing out while connecting to MySQL host.

1. Ensure MySQL running status

Here, we first checked the status of MySQL server. It was running fine on the server as per the snippet below.

● mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2019-03-09 15:25:43 xx; 2 weeks 5 days ago

Therefore, we isolated the problem with MySQL server status.

2. Correcting Configuration file

As the second step, we checked and confirmed that the script was using correct Database details including Hostname, User and Password. Moreover, the website was showing data from the database too. Thus, the connection was happening. The error was happening only at certain intervals.

Additionally, we checked that MySQL database user was able to connect from the command line.

3. Fixing server resources

Since we already ruled out configuration errors, the next thing to check was the server resources. Here, our Dedicated Engineers checked the memory usage on the server. We found that MySQL memory usage was high in the server (around 89% of available memory).

PID  USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                                                                             
30571 mysql     20   0 58.947g 0.055t   9832 S 135.1 89.2  16872:22 /usr/sbin/mysqld  

The memory usage statistics on the server looked as below.

We could see that there was a scope for MySQL tweaks in the server. Therefore, we analyzed the MySQL server performance by watching the MySQL queries and its impact on the server. Then our expert Database Engineers tweaked certain MySQL parameters such as join_buffer_size, table_open_cache and innodb_buffer_pool_instances.

After the tweaking, we restarted MySQL services at off-peak hours to minimize the impact on live websites. The performance on the MySQL server improved drastically and it fixed sqlstate hy000 error 2002 as well.

[Looking for tweaking MySQL server for improved performance? Our MySQL experts are available 24×7.]

Conclusion

In short, sqlstate hy000 error 2002 can happen due to stopped MySQL server, insufficient server resources, etc. Today we saw how our Dedicated Engineers troubleshooted and fixed MySQL errors for one of our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Понравилась статья? Поделить с друзьями:
  • Mysql ошибка 1241
  • Mysql ошибка 1146 как исправить
  • Mysql ошибка 1044
  • Mysql не удалось запустить службу ошибка 1067
  • Mysql код ошибки 1064