If you are running Ubuntu
via WSL (Windows Subsystem for Linux) and wish to connect to the MySQL instance on the host machine, you will need to use the host machine’s IPv4 address e.g. 192.X.X.X
, not 127.0.0.1
or localhost
.
$ mysql -u <user> -h 127.0.0.1 -p -P 3306
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (111)
$ mysql -u <user> -h 192.X.X.X -p -P 3306
Welcome to the MySQL monitor...Server version: 8.0.26 MySQL Community Server - GPL
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
To check your IPv4 address, go to Settings
-> Network $ Internet
-> Properties
-> IPv4 address
.
I got the same error configuring MySQL URI for apache airflow
as:
mysql+mysqlconnector://<user>:<password>@localhost:3306/<database>
(mysql.connector.errors.DatabaseError) 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (111)
or
mysql+mysqlconnector://<user>:<password>@127.0.0.1:3306/<database>
(mysql.connector.errors.DatabaseError) 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (111)
Fixed the error configuring the URI as:
mysql+mysqlconnector://<user>:<password>@192.X.X.X:3306/<database>
Asked
Viewed
110k times
I has had two days searching and exploring solutions regarding the error 2003.
Can’t connect to mysql server on ‘Server name’.
The firewall is off and I had added the port 3306, the one that mysql uses.
Any recommendation?
- mysql
- database-connection
- sqlyog
asked Nov 1, 2013 at 13:11
Sterling DiazSterling Diaz
3,7892 gold badges31 silver badges35 bronze badges
11 Answers
Please refer this FAQ which describes how to solve this issue: http://faq.webyog.com/content/23/15/en/error-no-2003-can_t-connect.html
Error No. 2003: Can’t connect to MySQL server on ‘localhost’ (or some other host)
simply means that connection is not possible for one of the following (or similar) reasons:
-
There is no MySQL server running at the specified host
-
Connection to the MySQL server is not allowed using TCP-IP. Check the ‘skip-networking’ setting in the MySQL configuration file (my.ini on Windows, my.cnf on Unix/Linux). It shall be commented out like ‘#skip-networking’. If it is not commented out, then do it and restart the MySQL server for the change to take effect. SQLyog needs to connect using TCP-IP.
-
Some networking issue prevents connection. It could be a network malconfiguration or a firewall issue.
-
When trying to connect to a MySQL server at an ISP this error message often indicates that direct connection to MySQL has been blocked. You must then use HTTP-tunneling or SSH-tunneling to connect.
answered Nov 5, 2013 at 12:03
Sathish DSathish D
4,85431 silver badges44 bronze badges
1
-
«Simply means», then lists four different, complex answers.
Feb 11, 2021 at 3:51
It worked for me.controll pannel->administrative tools->services->mysql and start mysql.Some times simple solution saves lot of time.
answered Nov 20, 2015 at 11:12
Mithun DebnathMithun Debnath
5881 gold badge8 silver badges23 bronze badges
normally means that there is no MySQL server running on the system .
check your server running
answered Apr 7, 2014 at 5:04
this could be due to firewalls of the system try below command and check
service iptables stop
answered Apr 16, 2014 at 10:31
user1397770user1397770
1353 silver badges16 bronze badges
i have the same issue but i fix it.
my hostname is DEBIAN, i just modify the file my.cnf ( for mysql) and set bindaddress : 0.0.0.0
this option say to mysql to listen all interfaces. restart your server and finish
answered Dec 7, 2016 at 9:35
if your question refer to can’t connect to mysql on hosting (cpanel), i also had same problem.
I also turn off firewall, but it doesn’t solve my problem.
Rather than using server name or domain name on Mysql Host Address, i using ip address given by hosting provider.
And it works.
Eric Aya
69.5k35 gold badges181 silver badges253 bronze badges
answered Dec 29, 2018 at 7:26
Going to services and starting MYSQL service doesn’t work for me.
Finally, I hit the following commands inside the MYSQL command-line client:
ALTER USER ‘username’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password’;
answered May 11, 2020 at 8:37
Sundar GautamSundar Gautam
4451 gold badge6 silver badges10 bronze badges
There is a high chance that you are making one of the two mistakes.
First :
You are inputting the wrong password. check your password or change it with
this command
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'very_strong_password';
In place of 'very_strong_password'
give a strong password of your choice.
Second:
You are using ‘@’ in the password which can be confused with the other with @localhost.
Saman Salehi
1,0041 gold badge12 silver badges19 bronze badges
answered Dec 14, 2021 at 14:21
1
-
Please fix formatting and spelling (you can use Grammarly or some service like this).
Dec 14, 2021 at 16:22
The SQL Sever might not be installed.
Please refer this to install:
MySQL
answered Aug 27, 2018 at 16:26
shreesh kattishreesh katti
7591 gold badge10 silver badges23 bronze badges
The solution worked for me
Go to services and start MySql services
window: press the start button and search services. Then star MySql services
answered Nov 20, 2022 at 16:04
Zia KhanZia Khan
1862 silver badges9 bronze badges
In my case main application installer will install mysql and try to connect with odbc. In that time it throws above error. The password given for configuring mysql was wrong. So I changed it.
Login as user root with blank password in mysql client.
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'abc';
Password changed and same password I used for configuration.
user16217248
3,19421 gold badges19 silver badges37 bronze badges
answered May 18 at 3:41
- The Overflow Blog
- Featured on Meta
Linked
Related
Hot Network Questions
-
How can I fix ammonia smell (from detergent buildup?) on «clean» cloth diapers?
-
MPQ4470-AEC1 Layout guideline clarification
-
How to get a dotted rule below every subsection title in scrartcl?
-
Setting beamer label from xparse option
-
Continue the Pattern #7
-
Will a Humans Tolerance Keep Going Until Full Immunity?
-
Transcript of discussion between Elon Musk and Israeli PM Benyamin Netanyahu on 18 Sep 2023?
-
How do I make my male character take off his bra?
-
Filter a list of strings to create a separate list of those that match a given prefix
-
Does a slippery liquid leak through pipe fittings?
-
How would mathematical demonstratives be used in a court?
-
Conjecture about partitions of the powerset without the empty set
-
Horizontal version of Print[]
-
Is Computer Modern 12 pt an exact scaled version of 10 pt? If not, how to scale?
-
The world’s smallest square maze?
-
Left a PhD for a second one from which I got fired. What to write in the CV?
-
Are integrated LEDs a riskier purchase than screw-in bulbs?
-
What happens if you ignore a howler?
-
Is it true that common law courts will not resolve a question without a controversy?
-
Transitioning between scenes in a novel
-
Can someone help me understand why the MAE, MSE and RMSE scores for my regression model are very low but the R2 is negative?
-
Peaks, plateaus and ledges
-
Dropship scammer hasn’t billed yet — what’s going on here?
-
How can a cybersecurity team mitigate internal customer complaints that real time user training is too intrusive?
more hot questions
Question feed
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
MySQL is one of the most popular engines for relational databases. It is mighty and provides many features that comply with Standard SQL out of the box.
Before you can use the MySQL database, you will need to set up and configure the MySQL server on your system. Thankfully, MySQL is cross-platform and provides installers for popular operating systems.
However, in some instances, you may encounter the “error 2003. Can’t connect to MySQL server on ‘localhost:3306′” error when attempting to login to MySQL.
In this tutorial, we will discuss the causes of this error and how you can resolve it.
What Causes this Error?
This error occurs when the MySQL Server is not running and cannot connect to the Server.
An example of this error is shown in the screenshot below:
Let us now discuss two techniques you can use to resolve this error.
How to Fix this Error?
There are two things you can do to fix this error:
- Ensure the MySQL Server is running on your system.
- Ensure you specify the target port if the Server is running on a different port.
Fix 1 – Ensure the MySQL Server is Running.
The first step is to verify that the server is running on your system. On your Windows terminal, use the command:
If you get the error shown below:
mysqlshow: Can‘t connect to MySQL server on ‘localhost:3306‘ (10061)
Then the Server is not running on your system.
To fix it, open the services manager on your Windows system. Press the Windows Key + R to launch the Run utility.
Next, enter “services.msc” and press enter.
In the Services Manager, scroll down until you locate the service for your MySQL server. For example, if you have MySQL version 5.0, the service will be under ‘MySQL50’, and MySQL version 8.0 will be under ‘MySQL80’, etc.
We have MySQL version 8 installed in the picture above. However, the service is not running as the Status tab is empty.
To fix this, right-click on the service name and press start. This should start the service and ensure the MySQL Server is running.
As you can see, the service status changes to ‘Running.’
Now we can connect to MySQL as:
In some cases, you may not find the MySQL service in the Services manager. In such a case, you will need to install the MySQL service.
Open the command prompt as an administrator and run the command:
The command above should install the MySQL service, allowing Windows to start and stop the service on startup.
Fix 2 – Verify MySQL Port
The MySQL Server will listen on a TCP port on your system. This is the port you will use to connect to the server.
If you have not made any changes to the running port during installation or in the configuration file, MySQL will run on port 3306.
You can verify under which port the server is running by checking the configuration file.
The MySQL configuration file is located in the directory:
C:\ProgramData\MySQL\MySQL Server 8.0
Under the name my.ini.
Open the file with your text editor and locate the [client] block. Find the entry defining the running port as shown:
Once you have the running port, you need to specify it when logging in to the server.
$ mysql -u root -p —port=[port_number]
NOTE that unless you know what you are doing, it is recommended to leave MySQL as the default running port.
If you changed the running port during installation, you can edit the configuration file and set it to 3306 or run the MySQL installer.
In the installer window, select ‘Reconfigure’ under MySQL Server.
Set the connectivity options in the Type and Networking section as TCP/IP and Port to 3306.
Follow along with the defaults and apply the changes.
Conclusion
In this article, we explored the causes of the “error 2003 (hy000) can’t connect to MySQL server on ‘localhost’ (10061)” error and various techniques to resolve it.
About the author
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list
This tutorial is intended to explain the necessary steps for solving the “ERROR 2003 (HY000): Can’t connect to MySQL server on ‘127.0.0.1’ (111)” which might occur when you try to access the MySQL database server.
Before moving any further, if you are a Linux user who is new to MySQL/MariaDB, then you may consider learning MySQL / MariaDB for Beginners – Part 1 and 20 MySQL (Mysqladmin) Commands for Database Administration in Linux as well.
On the other hand, if you are already a intermediate/experienced MySQL user, you can master these 15 Useful MySQL/MariaDB Performance Tuning and Optimization Tips.
Note: For this tutorial, it is assumed that you have already installed mysql database server.
Coming back to the point of focus, what are some of the possible causes of this error?
- Network failure especially if mysql database server is running on remote host.
- No mysql server is running on the mentioned host.
- Firewall blocking TCP-IP connection or other related reasons.
Below are the essential steps to deal with it.
1. If database server is on a remote machine, then try to test the client-server connectivity using ping
command, for instance:
$ ping server_ip_address
Once there is connectivity, use the ps
command below which shows information about a selection of the active processes, together with a pipe
and grep command, to check that the mysql daemon is running on your system.
$ ps -Af | grep mysqld
where the option:
-A
– activates selection of all processes-f
– enables full format listing
If there is no output from the previous command, start the mysql service as follows:
$ sudo systemctl start mysql.service $ sudo systemctl start mariadb.service OR # sudo /etc/init.d/mysqld start
After starting mysql service, try to access the database server:
$ mysql -u username -p -h host_address
2. If you still get the same error, then determine the port (default is 3306) on which the mysql daemon is listening by running the netstat command.
$ netstat -lnp | grep mysql
where the options:
-l
– displays listening ports-n
– enables display of numerical addresses-p
– shows PID and name of the program owning the socket
Therefore use the -P
option to specify the port you see from the output above while accessing the database server:
$ mysql -u username -p -h host_address -P port
3. If all the above commands run successfully, but you still see the error, open the mysql config file.
$ vi /etc/mysql/my.cnf OR $ vi /etc/mysql/mysql.conf.d/mysqld.cnf
Look for the line below and comment it out using the #
character:
bind-address = 127.0.0.1
Save the file and exit, afterwards restart the mysql service like so:
$ sudo systemctl start mysql.service $ sudo systemctl start mariadb.service OR # sudo /etc/init.d/mysqld start
However, if you have firewallD or Iptables running try to review firewall services and open the mysql port, assuming it is firewall blocking TCP-IP connections to your mysql server.
That’s all! Do you know other methods or have suggestions for solving the MySQL connection error above? Let us know by dropping a comment via the feedback form below.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Aaron Kili is a Linux and F.O.S.S enthusiast, an upcoming Linux SysAdmin, web developer, and currently a content creator for TecMint who loves working with computers and strongly believes in sharing knowledge.
Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.
Статья расскажет, как определять проблемы и ошибки на сервере баз данных 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"
Не удаётся подключиться к серверу 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
, чтобы получить от него ответ. - Если при подключении проблема не связана с сервером, проверьте, нормально ли работает клиент. Попробуйте получить какие-либо его выходные данные для устранения неполадок.
Избегаем часто встречающихся ошибок при работе с MySQL