Error mysql error number 2003

I use the following command: mysql -u root -h 127.0.0.1 -p And the error message is: ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111) How can I fix it?

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>

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»

Содержание

  1. Fix: ERROR 2003 (HY000): Can’t connect to MySQL server on ‘127.0.0.1’ (111)
  2. If You Appreciate What We Do Here On TecMint, You Should Consider:
  3. “mysqldump error 2003” – Here are the 3 important points to check
  4. “mysqldump error 2003” – A Brief explanation
  5. “mysqldump error 2003” – Why & How to fix?
  6. 1) MySQL service downtime
  7. 2) MySQL running on custom port
  8. 3) MySQL socket issues
  9. Conclusion

Fix: ERROR 2003 (HY000): Can’t connect to MySQL server on ‘127.0.0.1’ (111)

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?

  1. Network failure especially if mysql database server is running on remote host.
  2. No mysql server is running on the mentioned host.
  3. 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 Host Machine

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.

where the option:

  1. -A – activates selection of all processes
  2. -f – enables full format listing

Check MySQL Process

If there is no output from the previous command, start the mysql service as follows:

After starting mysql service, try to access the database server:

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.

where the options:

  1. -l – displays listening ports
  2. -n – enables display of numerical addresses
  3. -p – shows PID and name of the program owning the socket

Find MySQL Port Number

Therefore use the -P option to specify the port you see from the output above while accessing the database server:

3. If all the above commands run successfully, but you still see the error, open the mysql config file.

Look for the line below and comment it out using the # character:

Save the file and exit, afterwards restart the mysql service like so:

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.

Tutorial Feedback.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

“mysqldump error 2003” – Here are the 3 important points to check

Mysqldump is a useful tool for server owners to fully backup their databases.

However, many users come up with errors while doing a backup or restore using this tool. And, one such error is “mysqldump error 2003“.

At Bobcares, we help server owners resolve these errors as part of our Server Management Services.

Today, we’ll discuss the top 3 reasons for this error and how we fix them.

“mysqldump error 2003” – A Brief explanation

“Mysqldump error 2003” means that the network connection has been refused. And, users see the complete error message like this when using the mysqldump command.

This may be due to the downtime of MySQL service, disabled network connections, and more.

“mysqldump error 2003” – Why & How to fix?

We got a clear understanding of this error. Let’s now see the main reasons for this error and how our Support Engineers fix them.

1) MySQL service downtime

This error occurs usually if the MySQL service is not running on the server. There are scenarios in which MySQL server doesn’t automatically start after server reboots. Similarly, intermittent MySQL service crashes can also cause this error.

And, users see the ‘mysqldump error 2003‘ when trying to backup/restore the database.

Solution

Firstly, our hosting engineers check if the MySQL service is running on the server. For example on Linux servers, we use the following command to check the status of the MySQL service.

If the MySQL service is down or doesn’t respond, we’ll kill the MySQL dead processes and restart the service. Moreover, we modify the server configuration to start the MySQL service automatically during server reboot.

Similarly, intermittent service crashes can occur due to resource outages, heavy traffic, DDoS attacks, corrupted data files or index files, and more. Here, our Server Experts checks the server error logs to determine where the MySQL service failed and fix that issue.

2) MySQL running on custom port

The default port of MySQL is 3306. But, server owners prefer to use a custom port to improve security. So, in such cases users should explicitly specify the MySQL port to perform database operations.

In other words, if users use a custom MySQL port and use the mysqldump command without a custom port, the MySQL server will look for the default MySQL port and throws this error.

Solution

Our Hosting Engineers use the netstat command to find the right port on which the MySQL service is listening.

Once we have identified the correct MySQL port, we suggest customers to use the MySQL port explicitly in the mysqldump command. For example, see the below command.

In addition to that, we confirm that there are no syntax errors in the mysqldump command issued by the user.

3) MySQL socket issues

MySQL socket file is a pseudo file used by the server and clients to exchange requests and data. So, a missing socket file or wrong permissions of the socket file can lead to this error.

a) Missing MySQL socket file

The default location of MySQL socket file is /tmp/mysql.sock. In some servers, any users can delete the files in the /tmp directory which can lead to problems. We’ve seen cases where users mistakenly delete this file or create a custom cron to remove older files in /tmp folder.

Solution

Firstly, our Hosting Engineers check if the MySQL socket file that mysqladmin tries to access really exists. If not, we’ll restart the MySQL service which will create the mysql.sock file again.

Further, we protect the /tmp directory, so that the files can only be removed by their owners or root users. Alternatively in some cases, we change the default location of the MySQL socket. Similarly, if we find any cron entries removing the MySQL socket files, we’ll remove it from the server.

b) Wrong permission of MySQL socket file

Sometimes, the server has no proper access rights for the MySQL socket file or the directory that holds the MySQL socket file. If the server can’t access the socket file to communicate, it leads to this error.

Solution

Our Support Engineers correct the access privileges for the socket file and the directory, so that the server can connect to MySQL socket file for communication.

[And, do you need a MySQL Expert to look into this issue? Click here, we are online 24/7.]

Conclusion

In short, mysqldump error 2003 can occur due to MySQL service downtime, MySQL socket issues, and so on. Today, we’ve discussed the top 3 reasons for this error and how our Support Engineers fix this problem.

Источник

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?

  1. Network failure especially if mysql database server is running on remote host.
  2. No mysql server is running on the mentioned host.
  3. 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

Ping Host Machine

Ping Host Machine

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:

  1. -A – activates selection of all processes
  2. -f – enables full format listing

Check MySQL Process

Check MySQL Process

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:

  1. -l – displays listening ports
  2. -n – enables display of numerical addresses
  3. -p – shows PID and name of the program owning the socket

Find MySQL Port Number

Find MySQL Port Number

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 Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Mysqldump is a useful tool for server owners to fully backup their databases.

However, many users come up with errors while doing a backup or restore using this tool. And, one such error is “mysqldump error 2003“.

At Bobcares, we help server owners resolve these errors as part of our Server Management Services.

Today, we’ll discuss the top 3 reasons for this error and how we fix them.

“mysqldump error 2003” – A Brief explanation

“Mysqldump error 2003” means that the network connection has been refused. And, users see the complete error message like this when using the mysqldump command.

mysqldump: Got error: 2003: Can't connect to MySQL server on 'localhost' (10061) when trying to connect

This may be due to the downtime of MySQL service, disabled network connections, and more.

“mysqldump error 2003” – Why & How to fix?

We got a clear understanding of this error. Let’s now see the main reasons for this error and how our Support Engineers fix them.

1) MySQL service downtime

This error occurs usually if the MySQL service is not running on the server. There are scenarios in which MySQL server  doesn’t automatically start after server reboots. Similarly, intermittent MySQL service crashes can also cause this error.

And, users see the ‘mysqldump error 2003‘ when trying to backup/restore the database.

Solution

Firstly, our hosting engineers check if the MySQL service is running on the server. For example on Linux servers, we use the following command to check the status of the MySQL service.

ps aux | grep mysql

If the MySQL service is down or doesn’t respond, we’ll kill the MySQL dead processes and restart the service. Moreover, we modify the server configuration to start the MySQL service automatically during server reboot.

Similarly, intermittent service crashes can occur due to resource outages, heavy traffic, DDoS attacks, corrupted data files or index files, and more. Here, our Server Experts checks the server error logs to determine where the MySQL service failed and fix that issue.

[MySQL service keeps crashing on your server? Click here to get an experienced MySQL expert to fix it for you.]

2) MySQL running on custom port

The default port of MySQL is 3306. But, server owners prefer to use a custom port to improve security. So, in such cases users should explicitly specify the MySQL port to perform database operations.

In other words, if users use a custom MySQL port and use the mysqldump command without a custom port, the MySQL server will look for the default MySQL port and throws this error.

Solution

Our Hosting Engineers use the netstat command to find the right port on which the MySQL service is listening.

netstat -lnp | grep mysql

Once we have identified the correct MySQL port, we suggest customers to use the MySQL port explicitly in the mysqldump command. For example, see the below command.

mysqldump -u root -p password -P customport databasename > backup.sql

In addition to that, we confirm that there are no syntax errors in the mysqldump command issued by the user.

3) MySQL socket issues

MySQL socket file is a pseudo file used by the server and clients to exchange requests and data. So, a missing socket file or wrong permissions of the socket file can lead to this error.

a) Missing MySQL socket file

The default location of MySQL socket file is /tmp/mysql.sock. In some servers, any users can delete the files in the /tmp directory which can lead to problems. We’ve seen cases where users mistakenly delete this file or create a custom cron to remove older files in /tmp folder.

Solution

Firstly, our Hosting Engineers check if the MySQL socket file that mysqladmin tries to access really exists. If not, we’ll restart the MySQL service which will create the mysql.sock file again.

Further, we protect the /tmp directory, so that the files can only be removed by their owners or root users. Alternatively in some cases, we change the default location of the MySQL socket. Similarly, if we find any cron entries removing the MySQL socket files, we’ll remove it from the server.

b) Wrong permission of MySQL socket file

Sometimes, the server has no proper access rights for the MySQL socket file or the directory that holds the MySQL socket file. If the server can’t access the socket file to communicate, it leads to this error.

Solution

Our Support Engineers correct the access privileges for the socket file and the directory, so that the server can connect to MySQL socket file for communication.

[And, do you need a MySQL Expert to look into this issue? Click here, we are online 24/7.]

Conclusion

In short, mysqldump error 2003 can occur due to MySQL service downtime, MySQL socket issues, and so on. Today, we’ve discussed the top 3 reasons for this error and how our Support Engineers fix this problem.

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.

SEE SERVER ADMIN PLANS

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

За последние 24 часа нас посетили 11411 программистов и 1154 робота. Сейчас ищут 383 программиста …


  1. niko42

    niko42
    Активный пользователь

    С нами с:
    6 мар 2011
    Сообщения:
    16
    Симпатии:
    0

    Здравствуйте уважаемые дамы и госпола.

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

    Суть всего:
    Сервер стоит отдельно на IP 192.168.1.233, я же в свое время работаю с IP 192.168.1.3, удаленнка.
    Создал отдельного пользователя, наделил полными правами, а так же указал пользователю хост: %, т.е. ‘user’@’%’

    Захожу я этим пользователям через браузер http://192.168.1.233/phpmyadmin — все отлично заходит.

    Пытаюсь я присоединиться этим пользователям через программу Navicat и мне выдает ошибку, мол не могу присоединится к БД.

    Уточните, пожалуйста, в чем может быть беда?


  2. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

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

    может разрешен конект к базе только с той же машины? в свойсвах этой бд посмотри через браузер.


  3. niko42

    niko42
    Активный пользователь

    С нами с:
    6 мар 2011
    Сообщения:
    16
    Симпатии:
    0

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

    Дело в том, что у данного пользователя ALL PRIVILEGES — ко всем таблицам.


  4. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

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

    да. но подключение может быть разрешено только с локалхоста. проверь.


  5. niko42

    niko42
    Активный пользователь

    С нами с:
    6 мар 2011
    Сообщения:
    16
    Симпатии:
    0

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

    хост: %, т.е. ‘user’@’%’ — любой хост

    MySql сервер перезагружал и не раз, пользователя пересоздавал и не раз.
    создавал usera через phpmyadmin из под root
    /etc/init.d/mysql stop и start

    В самой таблице mysql
    `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `Event_priv`, `Trigger_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`) VALUES
    (‘%’, ‘user’, ‘*97816D5DE94608621FFDDA92B4597F0536762D27’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘Y’, », », », », 0, 0, 0, 0);


  6. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

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

    =( я не заметил. а это правильная запись?


  7. niko42

    niko42
    Активный пользователь

    С нами с:
    6 мар 2011
    Сообщения:
    16
    Симпатии:
    0

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

    Ну если бы запись была не верной, то я бы наврятли зашел данным пользователем через phpmyadmin

    MySQL
    Сервер: Localhost via UNIX socket
    Версия сервера: 5.1.49-3
    Версия протокола: 10
    Пользователь: user@localhost
    MySQL-кодировка: UTF-8 Unicode (utf8)
    Веб-сервер
    Apache/2.2.16 (Debian)
    Версия MySQL-клиента: 5.1.49
    PHP расширение: mysqli
    phpMyAdmin
    Информация о версии: 3.3.7deb7


  8. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768

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

    хз. может порт не тот? =) какие еще варианты…


  9. niko42

    niko42
    Активный пользователь

    С нами с:
    6 мар 2011
    Сообщения:
    16
    Симпатии:
    0

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

    # Remember to edit /etc/mysql/debian.cnf when changing the socket location.
    [client]
    port = 3306
    socket = /var/run/mysqld/mysqld.sock

    # This was formally known as [safe_mysqld]. Both versions are currently parsed.
    [mysqld_safe]
    socket = /var/run/mysqld/mysqld.sock
    nice = 0

    [mysqld]
    #
    # * Basic Settings
    #
    user = mysql
    pid-file = /var/run/mysqld/mysqld.pid
    socket = /var/run/mysqld/mysqld.sock
    port = 3306
    basedir = /usr
    datadir = /var/lib/mysql
    tmpdir = /tmp
    language = /usr/share/mysql/english
    skip-external-locking
    #
    # Instead of skip-networking the default is now to listen only on
    # localhost which is more compatible and is not less secure.
    bind-address = 127.0.0.1

    Добавлено спустя 42 минуты 56 секунд:
    Re: Ошибка: #2003 — Can’t connect to MySQL server on ‘192.168.1.
    Решил данный вопрос.

    В mysql конфиге, есть строчка bind-address = 127.0.0.1
    Данную строчку нужно закоментировать #bind-address = 127.0.0.1

При попытке подключиться к MySQL или Percona сервер с настройками по-умолчанию с другой рабочей станции или сервера, можно получить ошибку
ERROR 2003 (HY000): Can’t connect to MySQL server on ‘xx.xx.xx.xx’ (111)

Далее описаны 3 шага, которые нужно пройти для установления соединения.

The first thing we can check is to see if the user from the remote host is allowed.

1. Login as root on mysql server
mysql -u root -p

2. Select database and show users.
select * from mysql.userG

**A vertical list will be displayed. Look at the first two fields for each entry. If the user is only allowed to connect from localhost, this may be the problem.
Example:

Host: localhost
User: mydbuser

A user will have to be defined with the same parameters as mydbuser for the remote host (or hosts)
Here’s where your documentation will come in handy (or you can hope the old query exists in the mysql buffer!)

3. Allow remote hosts to connect
grant select,insert,update,delete,create,drop,index,alter on mydbname.* to mydbuser@’192.168.1.%’ identified by ‘mydbpassword’ ;

flush privileges;

Note: if you only want to allow a certain host, specify the IP instead of the wildcard.

The second issue that may cause this error is a MySQL configuration.

1. Open MySQL config file
nano /etc/my.cnf

2. Ensure that the following are commented out.

#skip-external-locking
#skip-networking
#bind-address = xx.xx.xx.xx

Save and exit

3. Restart mysql service
service mysqld start

The third issue that may contribute to this error may be the security configuration rejecting incoming requests on the server.

1. Login as root on db server

2. Add rule to iptables
/sbin/iptables -A INPUT -i eth0 -s 192.168.1.0/24 -p tcp —destination-port 3306 -j ACCEPT

** this grants access to the entire subnet, use a specific IP where applicable.

service iptables save

3. Restart iptables service
service iptables restart

Test from remote host by using the following:
mysql -h 192.168.my.dbip -u mydbuser -p

I have 2 MySQL servers named esDB1 esDB2 and an isolative MaxScale server.
All installed in CentOS 7 with installed information as:

[root@esDB1 ~]# cat /etc/centos-release
CentOS Linux release 7.4.1708 (Core) 
[root@esDB1 ~]#

[root@esDB1 ~]# yum list installed | grep -i mysql
mysql-commercial-client.x86_64        8.0.15-1.1.el7                   installed
mysql-commercial-common.x86_64        8.0.15-1.1.el7                   installed
mysql-commercial-libs.x86_64          8.0.15-1.1.el7                   installed
mysql-commercial-libs-compat.x86_64   8.0.15-1.1.el7                   installed
mysql-commercial-server.x86_64        8.0.15-1.1.el7                   installed
[root@esDB1 ~]#

[root@esMax1 ~]# yum list installed | grep -i maxscale
Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
maxscale.x86_64                      2.4.2-1                           installed
[root@esMax1 ~]#

There are 2 users for MaxScale in DB:

mysql> SHOW GRANTS for "MaxMonitor"@"168.6.42.%";
+--------------------------------------------------------------+
| Grants for MaxMonitor@168.6.42.%                             |
+--------------------------------------------------------------+
| GRANT REPLICATION CLIENT ON *.* TO `MaxMonitor`@`168.6.42.%` |
+--------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SHOW GRANTS for "MaxService"@"168.6.42.%";
+----------------------------------------------------------+
| Grants for MaxService@168.6.42.%                         |
+----------------------------------------------------------+
| GRANT SHOW DATABASES ON *.* TO `MaxService`@`168.6.42.%` |
| GRANT SELECT ON `mysql`.* TO `MaxService`@`168.6.42.%`   |
+----------------------------------------------------------+
2 rows in set (0.00 sec)

mysql>

The content of maxscale.cnf is:

[maxscale]
threads=auto
retain_last_statements=5
dump_last_statements=on_error


[esDB1]
type=server
address=168.6.42.111
port=3026
protocol=MariaDBBackend

[esDB2]
type=server
address=168.6.42.112
port=3026
protocol=MariaDBBackend


[MariaDB-Monitor]
type=monitor
module=mariadbmon
servers=esDB1,esDB2
user=MaxMonitor
password=MaxMonitor's password
monitor_interval=2000


[Read-Write-Service]
type=service
router=readwritesplit
servers=esDB1,esDB2
user=MaxService
password=MaxService's password


[MaxAdmin-Service]
type=service
router=cli


[Read-Write-Listener]
type=listener
service=Read-Write-Service
protocol=MariaDBClient
port=3306


[MaxAdmin-Listener]
type=listener
service=MaxAdmin-Service
protocol=maxscaled
socket=default

It can normally use the user «MaxService» directly login DB and execute SQL command.

[root@esDB1 ~]# mysql -uMaxService -p -h168.6.42.111 -P3026
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 29833
Server version: 8.0.15-commercial MySQL Enterprise Server - Commercial

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql>

Then I start the MaxScale without any error:

[root@esMax1 ~]# systemctl start maxscale
[root@esMax1 ~]# systemctl status maxscale -l
● maxscale.service - MariaDB MaxScale Database Proxy
   Loaded: loaded (/usr/lib/systemd/system/maxscale.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2019-09-09 18:14:45 CST; 19s ago
  Process: 8378 ExecStart=/usr/bin/maxscale (code=exited, status=0/SUCCESS)
  Process: 8375 ExecStartPre=/usr/bin/install -d /var/lib/maxscale -o maxscale -g maxscale (code=exi
ted, status=0/SUCCESS)
  Process: 8372 ExecStartPre=/usr/bin/install -d /var/run/maxscale -o maxscale -g maxscale (code=exi
ted, status=0/SUCCESS)
 Main PID: 8379 (maxscale)
   CGroup: /system.slice/maxscale.service
           └─8379 /usr/bin/maxscale

Sep 09 18:14:45 esMax1 maxscale[8379]: Listening for connections at [/var/run/maxscale/maxadmin.sock]:0
Sep 09 18:14:45 esMax1 maxscale[8379]: Service 'MaxAdmin-Service' started (1/2)
Sep 09 18:14:45 esMax1 maxscale[8379]: Server 'esDB1' version: 8.0.15-commercial
Sep 09 18:14:45 esMax1 maxscale[8379]: Server 'esDB2' version: 8.0.15-commercial
Sep 09 18:14:45 esMax1 maxscale[8379]: [MariaDBAuth] [Read-Write-Service] Loaded 17 MySQL users for listener Read-Write-Listener from server esDB1.
Sep 09 18:14:45 esMax1 maxscale[8379]: Listening for connections at [::]:3306
Sep 09 18:14:45 esMax1 maxscale[8379]: Service 'Read-Write-Service' started (2/2)
Sep 09 18:14:45 esMax1 maxscale[8379]: Loaded server states from journal file: /var/lib/maxscale/MariaDB-Monitor/monitor.dat
Sep 09 18:14:45 esMax1 systemd[1]: Started MariaDB MaxScale Database Proxy.
Sep 09 18:14:45 esMax1 maxscale[8379]: [mariadbmon] Attempted to find a replacement for the current 
master server 'esDB1' because it has started replicating from another server in the cluster, but 'esDB1' is still the best master server.
[root@esMax1 ~]#

The content of maxscale.log is:

MariaDB MaxScale  /var/log/maxscale/maxscale.log  Mon Sep  9 18:14:45 2019
----------------------------------------------------------------------------
2019-09-09 18:14:45   notice : syslog logging is enabled.
2019-09-09 18:14:45   notice : maxlog logging is enabled.
2019-09-09 18:14:45   notice : Using up to 548.00MiB of memory for query classifier cache
2019-09-09 18:14:45   notice : Working directory: /var/log/maxscale
2019-09-09 18:14:45   notice : The collection of SQLite memory allocation statistics turned off.
2019-09-09 18:14:45   notice : Threading mode of SQLite set to Multi-thread.
2019-09-09 18:14:45   notice : MariaDB MaxScale 2.4.2 started (Commit: aad4148d77bf2dfbaa0042bc45abda30c101cad2)
2019-09-09 18:14:45   notice : MaxScale is running in process 8379
2019-09-09 18:14:45   notice : Configuration file: /etc/maxscale.cnf
2019-09-09 18:14:45   notice : Log directory: /var/log/maxscale
2019-09-09 18:14:45   notice : Data directory: /var/lib/maxscale
2019-09-09 18:14:45   notice : Module directory: /usr/lib64/maxscale
2019-09-09 18:14:45   notice : Service cache: /var/cache/maxscale
2019-09-09 18:14:45   notice : No query classifier specified, using default 'qc_sqlite'.
2019-09-09 18:14:45   notice : Loaded module qc_sqlite: V1.0.0 from /usr/lib64/maxscale/libqc_sqlite.so
2019-09-09 18:14:45   notice : Query classification results are cached and reused. Memory used per thread: 137.00MiB
2019-09-09 18:14:45   notice : The systemd watchdog is Enabled. Internal timeout = 30s
2019-09-09 18:14:45   notice : Loading /etc/maxscale.cnf.
2019-09-09 18:14:45   notice : /etc/maxscale.cnf.d does not exist, not reading.
2019-09-09 18:14:45   notice : Loaded module maxscaled: V2.0.0 from /usr/lib64/maxscale/libmaxscaled.so
2019-09-09 18:14:45   notice : Loaded module MariaDBClient: V1.1.0 from /usr/lib64/maxscale/libmariadbclient.so
2019-09-09 18:14:45   warning: [cli] THE 'cli' MODULE AND 'maxadmin' ARE DEPRECATED: Use 'maxctrl' instead
2019-09-09 18:14:45   notice : Loaded module cli: V1.0.0 from /usr/lib64/maxscale/libcli.so
2019-09-09 18:14:45   notice : [readwritesplit] Initializing statement-based read/write split router module.
2019-09-09 18:14:45   notice : Loaded module readwritesplit: V1.1.0 from /usr/lib64/maxscale/libreadwritesplit.so
2019-09-09 18:14:45   notice : [mariadbmon] Initialise the MariaDB Monitor module.
2019-09-09 18:14:45   notice : Loaded module mariadbmon: V1.5.0 from /usr/lib64/maxscale/libmariadbmon.so
2019-09-09 18:14:45   notice : Loaded module MariaDBBackend: V2.0.0 from /usr/lib64/maxscale/libmariadbbackend.so
2019-09-09 18:14:45   notice : Loaded module mariadbbackendauth: V1.0.0 from /usr/lib64/maxscale/libmariadbbackendauth.so
2019-09-09 18:14:45   notice : Using encrypted passwords. Encryption key: '/var/lib/maxscale/.secrets'.
2019-09-09 18:14:45   notice : Loaded module MaxAdminAuth: V2.1.0 from /usr/lib64/maxscale/libmaxadminauth.so
2019-09-09 18:14:45   notice : Loaded module mariadbauth: V1.1.0 from /usr/lib64/maxscale/libmariadbauth.so
2019-09-09 18:14:45   notice : Started REST API on [127.0.0.1]:8989
2019-09-09 18:14:45   notice : MaxScale started with 4 worker threads, each with a stack size of 8388608 bytes.
2019-09-09 18:14:45   notice : Starting a total of 2 services...
2019-09-09 18:14:45   notice : Listening for connections at [/var/run/maxscale/maxadmin.sock]:0
2019-09-09 18:14:45   notice : Service 'MaxAdmin-Service' started (1/2)
2019-09-09 18:14:45   notice : Server 'esDB1' version: 8.0.15-commercial
2019-09-09 18:14:45   notice : Server 'esDB2' version: 8.0.15-commercial
2019-09-09 18:14:45   notice : [MariaDBAuth] [Read-Write-Service] Loaded 17 MySQL users for listener Read-Write-Listener from server esDB1.
2019-09-09 18:14:45   notice : Listening for connections at [::]:3306
2019-09-09 18:14:45   notice : Service 'Read-Write-Service' started (2/2)
2019-09-09 18:14:45   notice : Loaded server states from journal file: /var/lib/maxscale/MariaDB-Monitor/monitor.dat
2019-09-09 18:14:45   warning: [mariadbmon] Attempted to find a replacement for the current master server 'esDB1' because it has started replicating from another server in the cluster, but 'esDB1' is still the best master server.

And then I can use all user’s ID to login through MaxScale, but can not execute any SQL command:

[root@esMax1 ~]# mysql -uMaxService -p -h168.6.42.118
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 1
Server version: 5.5.5-8.0.15-commercial

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

mysql>
mysql> show databases;
ERROR 2003 (HY000): Authentication with backend failed. Session will be closed.
mysql> show databases;
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    2
Current database: *** NONE ***

ERROR 2003 (HY000): Authentication with backend failed. Session will be closed.
mysql>

The content of maxscale.cnf added 6 records as:

2019-09-09 18:19:35   error  : [mariadbbackend] Unable to write to backend 'esDB1' due to authentication failure. Server in state Master, Running.
2019-09-09 18:19:35   error  : [mariadbbackend] Unable to write to backend 'esDB2' due to authentication failure. Server in state Relay Master, Slave, Running.
2019-09-09 18:19:35   notice : (1) Stmt 1(1970-01-01 08:00:00): select @@version_comment limit 1
2019-09-09 18:20:04   error  : [mariadbbackend] Unable to write to backend 'esDB2' due to authentication failure. Server in state Relay Master, Slave, Running.
2019-09-09 18:20:04   notice : (2) Stmt 1(1970-01-01 08:00:00): show databases
2019-09-09 18:20:04   error  : [mariadbbackend] Unable to write to backend 'esDB1' due to authentication failure. Server in state Master, Running.

Can anyone help me to correct it?

You have to configure the backends with default_authentication_plugin=mysql_native_password, MySQL 8.0 uses the caching_sha2_password plugin by default.

Понравилась статья? Поделить с друзьями:
  • Error mysql 76 fell through ecase expression
  • Error mxm structure not found or invalid решение
  • Error mutex does not name a type
  • Error must specify org id or org name
  • Error must run as root ubuntu