Mysql error 2003 hy000 can t connect to mysql server on localhost 10061

Learn how to fix MySQL error can't connect to the server

When you’re done installing a MySQL server application on Windows operating system, you can try to login to your MySQL server by using the mysql command from the Command Line.

But sometimes you may get the MySQL 2003 error saying it can’t connect to MySQL server as shown below:

mysql --user=[your username] --password=[your password]
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (10061)

The error above means that your request to connect to the MySQL server has been refused.

There are two things you need to check to fix this error:

  • Make sure that your MySQL service is actually running
  • Check that you are attempting to connect to the right port number

This tutorial will help you to do both, starting with checking MySQL service status.

Make sure that your MySQL service is actually running

To fix this error, you need to make sure that your MySQL server service is actually running in the Services panel.

First, 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.

MySQL service is missing from the Services panel

If you don’t find MySQL service from the Services panel, then you may not have installed MySQL as a Windows service.

It’s always recommended to install MySQL as a Windows service so that you can start and stop a running MySQL program easily.

To install the MySQL service, you can run the mysqld --install command from the command line as follows:

mysqld --install
Service successfully installed.

Please note that you need to have Administrator access to perform the installation above.

Alternatively, you can re-run the MySQL installer program and choose to reconfigure the installed MySQL server as shown below:

In the reconfigure wizard panel, click on Next until you get into the Windows Service section.

You should check the box that says Configure MySQL Server as a Windows Service as follows:

When you’re done, click on Next and then click on Execute to run the changes.

Now you should be able to find MySQL under the Services panel.

Check that you are attempting to connect to the right port number

When you run a MySQL service on your computer, the service will start MySQL server and allows you to connect to the server under a specific port number.

By default MySQL uses port 3306 but you can check the one you are currently using in your my.ini file.

The my.ini file is a MySQL configuration file used to properly configure the running MySQL services.

When you install MySQL using the official installer, then you should have a my.ini file located under your MySQL installation folder.

For example, mine was located under C:ProgramDataMySQLMySQL Server 8.0 folder as shown below:

Once you find the file, open it and find the [client] section.

You should find the port number assigned under the section as shown below:

[client]

# pipe=

# socket=MYSQL

port=3306

[mysql]
no-beep

Once you find the port number, and the number to the mysql command when you try to login as follows:

mysql --user=[your username] --password=[your password] --port=3306

Now you should be able to connect to your local MySQL server. Nice work! 👍


When you are working with a MySQL database, you might run into this error:

2003 - Can't connect to MySQL server on '127.0.0.1' (or some other host)

There might be several causes for that error, so you can try these methods to find out what the problem is.

1. Check for typos

A small typo in the MySQL server name, database name, username, port, etc. can lead to this error, so make sure you got them right 100%.

2. Make sure MySQL server is running

Maybe the problem is that there is no MySQL server running at the specified host. So the first thing you should do is to verify the status of MySQL Server. It’s recommended to try restarting the MySQL server.

You might need to check the port that it’s listening to, the default port is 3306.

If you are using DBngin to manage the local server, launch DBngin and see if the server is still on. If not, start it.

DBngin

3. Connection to the MySQL server is not allowed using TCP/IP

You need to make sure that your MySQL server was not started with the --skip-networking option. You should find the setting in the MySQL configuration file (my.ini on Windows, my.cnf on Unix/Linux).

If it was, remove it and restart MySQL server for the change to take effect.

For remote connections, you need to confirm that MySQL remote access is enabled. By default, MySQL listens for connections only from localhost. Go check the MySQL configuration file and give the bind-address as the IP address of the server where MySQL service listens.

You could also try increasing the max_connection parameter in the MySQL configuration file.

4. There is a networking issue blocking access to MySQL

It could be a network firewall blocking the connection. Most often it will help to uninstall and reinstall the firewall.

5. Still no help at all?

If you tried all above and none of them worked, try connecting using SSH Tunnelling instead and see if it helps.

For more information, visit MySQL Reference Manual.


Need a good MySQL GUI? TablePlus provides a native client that allows you to access and manage MySQL and many other databases simultaneously using an intuitive and powerful graphical interface.

Download TablePlus for Mac.

Not on Mac? Download TablePlus for Windows.

Need a quick edit on the go? Download for iOS

TablePlus in Dark mode

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»


Home
→ MySQL

|In: MySQL|Last Updated: September 14, 2022

I have installed MySQL version 5.6 on windows 7. My Installation was successful and without any error. I received “ERROR 2003 (HY000): Can’t connect to MySQL server on ‘localhost’ (10061)” while I was trying to start MySQL server from command prompt. I am attaching the screenshot of the error I received.

Image of command prompt while starting MySQL Server
Starting MySQL From Command Prompt

When I could not connect to MySQL server installed on my windows. I tried to connect MySQL Server directly by using “MySQL5.6 Command Line Client”. Same error was occurring and MySQL Command line was disappearing.

I was little worried of this error – ERROR 2003 (HY000). I did not get any of issues while installing MySQL5.6 on windows so MySQL server should work properly.
I did search on internet (MySQL forum, DB related forums) and I resolved Can’t connect to MySQL server on ‘localhost’ (10061) error. Now I was able to run MySQL server from command prompt.

Reason for ERROR 2003 (HY000): Can’t connect to MySQL server on ‘localhost’ (10061) – MySQL services has not been started.

Please see the steps below to fix this problem.

1. Please Log in as Admin to your System.
2. Open your Task Manager panel.
3. Go to Services tab.
4. See there for MySQL presence. It will look like this image given below.In my case it is displayed like MySQL56.

Image Showing Services tab in Task Manager
Showing MySQL Services Status using Task Manager

In the above image you can see that MySQL56 service is showing as Stopped. Please see the blue dark line in the image.

5. Please select MySQL56 and do right click. You will get Start option. Select Start command to start MySQL Services. Please see the below image for your reference.

Image displaying how to start mysql server from task manager services tab
Image Showing how to start MySQL server from task manager

6. Please recheck that MySQL service has been started successfully.
7. In case MySQL services do not start using this way, It means you are not logged in with Admin account. In this case you will receive this error.

Access is not possible
Getting Error if not logged in as Admin

Please follow next given steps to start MySQL service from Administrative Panel.
8. Please Go to  Control Panel > All Control Panel Items > Administrative Tools.
9. Please go to Services. Below image is showing the process.

Showing Administrative tools
Image showing Services in Administrative Tools

10. Please select MySQL56 under Name column.
11. Please click on start link from left panel to start MySQL Service. Please see the image below for your reference.

Image showing how to install mysql server manually from services
Starting MySQL server from Administrative panel

12. Once MySQL service started. Please go to MySQL bin directory using command prompt and retype the command >mysql -u root -p mysql
13. Please enter your MySQL password.
14. We can see image given below after MySQL server started successfully.

Command prompt showing mysql server started successfully
MySQL Server Started Successfully from Command prompt

Thanks for reading this post. Please let me know if your problem has been resolved.

Finally, In case you want to learn how to install MySQL server from scratch please check this YouTube video. Please do not forget to subscribe to our Youtube channel.

Comments
(26)

Вы не вошли. Пожалуйста, войдите или зарегистрируйтесь.

Активные темы Темы без ответов

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 2007-07-28 22:26:49

  • wls972
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2007-07-28
  • Сообщений: 2

Тема: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

Привет всем!!! Столкнулся с такой ошибкой
Ошибка
Ответ MySQL: 

#2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

Помогите пожалуйста разобраться. Заранее благодарен.

2 Ответ от Hanut 2007-07-29 12:59:19

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,723

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

wls972
Проверьте запущен ли сервер MySQL и можно ли к нему подсоединиться через командную строку.

3 Ответ от wls972 2007-08-03 00:18:15

  • wls972
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2007-07-28
  • Сообщений: 2

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

Большое спасибо!!! На самом деле забыл включить MySQL. Постараюсь быть внимательней.

4 Ответ от mendosa 2007-10-04 10:14:56 (изменено: mendosa, 2007-10-04 10:16:15)

  • mendosa
  • Участник
  • Неактивен
  • Зарегистрирован: 2007-07-19
  • Сообщений: 66

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

У меня тоже самое.Но все включено.Подозреваю схватил что то типа вируса .Даже из командной строки после набора mysql -u root .MySQL5 куда рвется файволл не пускает .В результате выдает это сообщениеСобираюсь форматировать диск и устанавливать все заново.Что означает это сообщение? ведь порт mysql  3306. Может как то можно исправить?

5 Ответ от Hanut 2007-10-04 11:42:40

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,723

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

mendosa
У вас это сообщение именно из-за того что брандмауэр блокирует процесс MySQL.

6 Ответ от mendosa 2007-10-04 12:05:03

  • mendosa
  • Участник
  • Неактивен
  • Зарегистрирован: 2007-07-19
  • Сообщений: 66

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

проверил выключал брандмауэр и сеть .тоже самое.как запустить mysql чтобы посмотреть как работает.хотя неожиданно стало рваться в интернет MYSQLD-NT.EXE сейчас разрешил при перезагрузке разрешил но тничего не помогло снова при обращении к phpmyadmin возникает
2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

7 Ответ от Hanut 2007-10-04 21:30:04

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,723

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

mendosa
Не могу помочь. Причина не ясна.

8 Ответ от stylerr 2012-04-05 22:08:48

  • stylerr
  • Новичок
  • Неактивен
  • Зарегистрирован: 2012-04-05
  • Сообщений: 1

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

я пробовал через так
1. менял директорию на ту в которой бинарники мускуля лежат
2. логинился обычным образом mysql -u root -p

все прокатывало, а если из другой директории то как раз такая же ошибка

в чем прикол так и не раскурил пока

Влад

9 Ответ от Hanut 2012-04-05 23:58:51

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,723

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

stylerr сказал:

в чем прикол так и не раскурил пока

Возможно директория MySQL/bin не добавлена в PATH операционной системы.

10 Ответ от Stas 2012-07-21 08:42:26

  • Stas
  • Новичок
  • Неактивен
  • Зарегистрирован: 2012-07-21
  • Сообщений: 1

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

У меня такой глюк был когда я права на всю папку

11 Ответ от Don Alehandro 2013-12-05 10:05:59

  • Don Alehandro
  • Новичок
  • Неактивен
  • Зарегистрирован: 2013-12-05
  • Сообщений: 1

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

Здравствуйте) Помогите пожалуйста, у меня все запущено и брандмауэр отключен и все равно пишет 2003 — Can’t connect to MySQL server on ‘localhost’ (10061), а раньше все работало, а теперь почему та нет( помогите плиз)

12 Ответ от Hanut 2013-12-05 11:49:05

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,723

Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘localhost’ (10061)

Don Alehandro сказал:

Can’t connect to MySQL server on ‘localhost’ (10061)

Проверьте запущен ли сервис MySQL в службах. Если запущен, то попробуйте перезапустить.

Сообщения 12

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

A few months ago, when I installed MySQL server on Windows 10 to run WordPress locally, I chose to have the database files on my main SSD drive. As it was slowly filling up, I decided to migrate the MySQL database files to another drive. I assumed all I needed to do is to update a path for datadir option in my.ini configuration file, but that didn’t work. After the database location move, starting the MySQL server gave me the 10061 error «Can’t connect to MySQL server» error. Luckily, the fix was quite simple.

I got the following MySQL Workbench Connect error, when starting the MySQL server:

MySQL error - could not connect to MySQL - error code 10061 2003

Could not connect to MySQL: Can’t connect to MySQL Server on ‘localhost’ (10061) (code 2003)

The MySQL Notifier’s «Startup Message Log» contained the following:

Starting server…
Server start done.
Checking server status…
Trying to connect to MySQL…
Can’t connect to MySQL server on ‘localhost’ (10061) (2003)
Assuming server is not running

As I mentioned, the datadir option in the main my.ini configuration file didn’t work, but I also found my.ini file in the following path C:ProgramDataMySQLMySQL Server 5.7. I fixed the datadir path there too, but that didn’t do anything.

In the end, the solution for me was to reconfigure the MySQL Install.

To reconfigure the MySQL install, we do the following steps:

  1. In Start Menu, search for «mysql«. Among the results, you should see the «MySQL Installer — Community«. Run it.

    Note: If you don’t find it, open the Windows Explorer and find the MySQLInstaller.exe file inside the following path for Windows 10:
    C:Program Files (x86)MySQLMySQL Installer for Windows

  2. MySQL Installer window will show up as shown below. Find «MySQL Server» under Product and click on «Reconfigure» link.

    MySQL Installer Community

    Click image to enlarge

  3. The MySQL Installer will show up (the same one you used for the first MySQL Server installation). Go through all the steps.

    MySQL server installer

    Click image to enlarge

After the MySQL Installer was finished, I started the MySQL service again. This time, the «Startup Message Log» on The MySQL Notifier was showing that the server started successfully:

Starting server…
Server start done.
Checking server status…
Trying to connect to MySQL…
Connection succeeded
Assuming server is running

Conclusion

There are many suggestions on the web about how to solve the MySQL 10061 error. The one that worked for me was to run the MySQL Installer — Community and then choose «Reconfigure» for the MySQL server product. I hope you have found this article helpful. If you fixed this issue using another way, drop a comment and let us know.

Понравилась статья? Поделить с друзьями:
  • Mysql error 1644
  • Mysql error 1524 hy000 plugin 0 is not loaded
  • Mysql error 150
  • Mysql error 144
  • Mysql error 1410 42000 you are not allowed to create a user with grant