Error sqlstate hy000 2002 connection refused

The major reasons for sqlstate hy000 error 2002 include stopped MySQL server, insufficient server resources, incorrect database settings, etc.

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»;

Пытаюсь использовать YII локально с докером. Настроил БД. Миграции работают нормально, при этом когда пробую записать или прочитать что-то из таблицы user , к примеру, получаю ошибку :

Database Exception – yiidbException
SQLSTATE[HY000] [2002] Connection refused

Caused by: PDOException
SQLSTATE[HY000] [2002] Connection refused
in /var/www/project.test/vendor/yiisoft/yii2/db/Connection.php at line 687

Менял 127.0.0.1 на localhost.


  • Вопрос задан

    более трёх лет назад

  • 12778 просмотров

Правильный ответ
Пришлось сделать ДВА(!) конфига . Отдельно для консоли и для остального приложения. Разница в
dsn.

Для консоли
‘dsn’ => ‘mysql:host=127.0.0.1;dbname=project’,
Для остального приложения
‘dsn’ => ‘mysql:host=mysql;dbname=project’,

Пригласить эксперта

потому что у консольной команды и у сайта различные конфиги и коннекты. Ищите проблему в конфигах yii.


  • Показать ещё
    Загружается…

13 февр. 2023, в 17:43

3000 руб./за проект

13 февр. 2023, в 16:58

25000 руб./за проект

13 февр. 2023, в 16:52

5000 руб./за проект

Минуточку внимания

#1 31.07.2015 18:23:04

Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

Всем привет!
Вопрос такой, создал подключение к базе данных, миграции проходят. Стал выводить данные и получил такую ошибку.

PDOException in Connector.php line 50:
SQLSTATE[HY000] [2002] Connection refused

Гугл не помог, подскажите, может быть у кого-то была подобная проблема?
Использую homestead, но еще на компьютере установлен MAMP, может быть дело в этом?

#3 01.08.2015 12:11:14

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

Настройте конфигурацию подключения к бд в файле .env

#4 01.08.2015 13:52:43

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

Файл настроен, миграции проходят, но статьи не выводятся.
http://joxi.ru/zANpbxPsPXO6m9

#5 01.08.2015 14:26:03

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

Выявил такую ошибку, меняешь параметры в файле .env, но на сайте в дебагере они не меняются.

#6 01.08.2015 19:39:37

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

Я Вам написал, исправьте настройки в  .env

DB_HOST=ХОСТ
DB_DATABASE=БАЗА
DB_USERNAME=ЛОГИН
DB_PASSWORD=ПАРОЛЬ

и в database.php

		'mysql' => [
			'driver'    => 'mysql',
			'host'      => env('DB_HOST', 'ХОСТ'),
			'database'  => env('DB_DATABASE', 'БАЗА'),
			'username'  => env('DB_USERNAME', 'ЛОГИН'),
			'password'  => env('DB_PASSWORD', 'ПАРОЛЬ'),
			'charset'   => 'utf8',
			'collation' => 'utf8_unicode_ci',
			'prefix'    => '',
			'strict'    => false,
		],

#7 01.08.2015 19:40:19

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

По скриншоту видно, что у вас дефолтные настройки

#8 17.08.2015 13:31:37

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

fanaticus пишет:

По скриншоту видно, что у вас дефолтные настройки

Нифига не дефолтные, точнее кажется что это так…порт у него какой то марсианский 33060, а так вроде ниче так дефолт :-D

#9 04.09.2016 04:58:54

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

собственно кому полезно может будет.
Решение аналогичное Fanaticus.

правда машина — Мак, локалхост через Mamp.
после некоторых действий  тут
http://stackoverflow.com/questions/3250 … -with-mamp
переМэйкил контроллер связанный с миграцией.

#10 01.12.2018 12:39:36

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

У меня возникла такая же проблема на MAMP. Решил просто — включил галочку в настройках MySQL. Если кому-то поможет, тут скриншот экрана, на котором нужно включить настройку http://priscree.ru/img/bc59e5a1ee0c1c.png

#11 01.12.2018 13:08:32

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

@VovaMark2 а не может такого быть, что миграции ты выполняешь на одной машине (виртуальной), а вебсервер работает на другой (физической)? В такм случае localhost для них разный!!! Лучше всего всё делать на одном и том же хосте, но если очень хочется иметь доступ отовсюду, то надо указать IP где находится сервер БД и убедиться, что настроки MySQL позволят обращаться извне.

Другая идея состоит в том, что возможно настройки нормальные, но конфигурация не обновилась из-за кеширования. Решается через
php artisan config:clear
или
php artisan config:cache


There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.

#12 24.10.2021 18:33:09

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

artoodetoo, спасибо!
При переносе проекта на VPS такая же ошибка была.
Помогло обновление кэш
php artisan config:cache

#13 17.11.2022 21:18:56

Re: Ошибка базы данных SQLSTATE[HY000] [2002] Connection refused

Я запускаю laravel через docker-compose.

Мне помогло вот это

Так, как в docker-compose.yml прописано services: mysql

How I got this error?
Ans: I was running php artisan migrate command in /opt/lampp/htdocs/project_dir

What was the error?
ubuntu@ip-ip_addr:/opt/lampp/htdocs/project_dir$ php artisan migrate
In Connection.php line 664:

SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = db_name and table_name = migrations
)

In Connector.php line 67:

SQLSTATE[HY000] [2002] Connection refused

Screenshot of the error:

Solution:
1. Open .env file
2. Change the DB_HOST=127.0.0.1 to DB_HOST=localhost
3. Make sure the port number, db name, username and password is correctly mention in the .env before saving it
4. Save the .env file then run command: sudo artisan config:cache
5. Now, run command: php artisan migrate

Output after applying the solution:

Thanks for reading. I hope you enjoyed the article!

play

Laravel 5.5 CRUD Tutorial, Introduction And Agenda Overview, Laravel Training Part – 1 DevopsSchool

  • Author
  • Recent Posts

Chetan

https://www.linkedin.com/in/chetanacin/
Email — contact@DevOpsSchool.com

Chetan is a Full Stack Software developer. He provides optimize solutions at each and every layer of the Enterprise application right from Front end to back end using demanding next gen technologies.

Worked with renowned software companies like ATCS Inc USA, Mercedes Benz USA, Intel, McAfee, JDA Software Inc, Infosys Limited

Expertise in Java/J2ee, PHP, Laravel, Javacript, Angular JS, JQuery, Html, CSS, Git, Aws, Node

1. Technical consultation to customers
2. Trainer on Java, J2EE, JavaScript and PHP Laravel frameworks, PL/SQL, Cross Platform Mobile App Development
3. Team Conflict resolution. Great Team Player
4. Quick Learner. Ability to adapt & expertise new or unknown technologies very easily and quickly
3. Ux/ Mock up screens/ Wire frame designing Skills
4. Excellent development skills
5. Automation Testing skills
6. Server hosting & deployment skills
7. Middle ware/ Server Technologies: Java, J2EE, Spring MVC, Spring Security, Spring Core,Hibernate, Struts, REST Web Services.
8. Web Technologies: Sencha ExtJS, Angular JS, JQuery, Bootstrap CSS, Html, Css, Javascript
9. Mobile Technologies: Cordova/ Phonegap, Ionic
10. Server side build tools: Ant, Maven
11. Web UI side build tools: Node JS, Grunt JS
12. Version Control Tools: Git, SVN, Source Tree
13. Server Side Testing Technologies: JUnit, REST Assured
14. Frontend Side Testing Technologies: JS Unit, Mocha, Sinon

Chetan

Понравилась статья? Поделить с друзьями:
  • Error setfullscreen creating the device failed max payne
  • Error service unavailable message service unavailable
  • Error send key трофейная рыбалка
  • Error secure boot forbids loading module from
  • Error sans x cross sans