Php mysql 2002 connection refused

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SQLSTATE[HY000] [2002] Connection refused #1323

SQLSTATE[HY000] [2002] Connection refused #1323

Comments

Hello guys. Have a problem, and need help.

I clone laradock in /var/www/docker/laradock
than i make docker-compose up -d apache2 mysql

and in /var/www/docker i run laravel new project.

my laradock .env
MYSQL_VERSION=8.0
MYSQL_DATABASE=AriesDB
MYSQL_USER=default
MYSQL_PASSWORD=secret
MYSQL_PORT=3307
MYSQL_ROOT_PASSWORD=root
MYSQL_ENTRYPOINT_INITDB=./mysql/docker-entrypoint-initdb.d

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3307
DB_DATABASE=AriesDB
DB_USERNAME=root
DB_PASSWORD=root

when i do «php artisan migrate» and «php artisan db:seed» everything works ok
buy when i run my browser and put my login and password, show this messenger SQLSTATE[HY000] [2002] Connection refused (SQL: select * from users where email = rodrigo@com.br limit 1).

if i do docker-compose exec workspace bash, and try «php artisan migrate» show this messenger: SQLSTATE[HY000] [2002] Connection refused

I tryied change DB_HOST=127.0.0.1 to DB_HOST=mysql but nothing changed.
Can somebody help me?

The text was updated successfully, but these errors were encountered:

Источник

How do I fix the Mysql error “Connection refused”?

The MySQL server error SQLSTATE[HY000] [2002] Connection refused. can be caused by several reasons, if you follow the steps below you should be able to fix this issue:

  • Check that your config file config/config.ini.php (in the Matomo directory) contains the correct and up to date DB credentials under the [database] section. Check that the DB username, DB password, database host, and database port are correct. (if you are unsure, reach out to your database administrator or check in your web hosting account for the up to date credentials).
  • If the config file references host = «localhost» , you can try to change it to 127.0.0.1 instead, for example in your config.ini.php under [database] set host = «127.0.0.1» .
  • If the above changes do not resolve the issue, we recommend you try to connect to MySQL on the command line to check if the credentials are correct and the server works. Connect to the server running Matomo and run this command: mysql -h [hostname] -u [username] -p[password] -D [dbname] (and replace the parameters in [] by the values found in your config.ini.php file.).
  • If the command above works, but you still get the “Connection refused” error in the browser, there may be an issue with PHP. Please reach out to your web hosting company or system administrator.
  • Check that the MySQL Server is running. Connect to the server running the MySQL database and check if the MySQL server is actively running by running this command mysqladmin -u root -p status (which should return an output like this: Uptime: 172505 Threads: 2 Questions: 90 Slow queries: 0 Opens: 157 Flush tables: 3 Open tables: 76 )
  • If you find the DB server is not running, proceed to restart Mysql server (or rebooting the whole server).
  • Or If the Database server have run out of disk space and there is no space left on the server, it may also start to refuse connections.
  • Sometimes MySQL servers are configured to refused some connections (for example connections from outside the network). If your MySQL database is managed by your web hosting company, contact them as they may be able to help.

If you still have the SQLSTATE[HY000] [2002] Connection refused. after checking the steps above, feel free to reach out to us by clicking the feedback button below.

Источник

PHP Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY000] [2002] Connection refused

I have a different server for my database. When I connected to database with PDO, I used the IP address of database VM for host parameter:

$dbh = new pdo("mysql:host=192.168.56.103;port=3306;dbname=data",'root','root') 

But I get connection refused (PDOException’ with message ‘SQLSTATE[HY000] [2002]’). I guess it couldn’t find MySQL there. It could however, find the VM with that IP.

2 Answers 2

Well then check if mysql is really not running:

sudo aptitude install nmap 

You can also install the tool on the mysql server, the the command would be:

In both cases your answer should look like this.

[simmel]@[mars]$ sudo nmap -sS 172.16.1.41 Starting Nmap 6.40 ( http://nmap.org ) at 2015-04-08 15:09 CEST Nmap scan report for 172.16.1.41 Host is up (0.010s latency). Not shown: 996 closed ports PORT STATE SERVICE 3306/tcp open mysql Nmap done: 1 IP address (1 host up) scanned in 33.17 seconds 

If it shows you port 3306, it’s indeed open and ready for connections. If that is the case use mysql via command line from your computer.

The same message appears? Connection refused? Then your user has probably the wrong rights.

Another reason for this is when the mysql server is bound to a certain address, like 127.0.0.1.

To find out check the output from:

If mysql is not listening to 0.0.0.0:3306 but to 127.0.0.1:3306 , you only can connect from localhost.

To change that go to /etc/mysql/my.cnf and comment out the following line:

The way to comment it out is to add a leading # character:

Save the file and restart the mysql service

sudo service mysql restart 

Now you should be able to connect.

To change the port, enter, for example:

Save the file and restart the mysql service:

sudo service mysql restart 

the message is : not shown:999 closed port , PORT STATE SERVICE , 80 tcp open http . it didnt show 3306

The error 2002 means that MySQL can’t connect to local database server through the socket file (e.g. /tmp/mysql.sock ).

To find out where is your socket file, run:

then double check that your application uses the right Unix socket file or connect through the TCP/IP port instead.

mysql --socket=/var/mysql/mysql.sock 

If the Unix socket is wrong, you may symlink it, for example:

ln -vs /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock 

or correct your configuration file (e.g. php.ini ).

To test the PDO connection directly from PHP, you may run:

php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8;dbname=dbname', 'root', 'root');" 

Check also the configuration between Apache and CLI (command-line interface), as the configuration can be differ.

It might be that the server is running, but you are trying to connect using a TCP/IP port, named pipe, or Unix socket file different from the one on which the server is listening. To correct that you need to invoke a client program (e.g. specifying —port option) to indicate the proper port number, or the proper named pipe or Unix socket file (e.g. —socket option).

Other utils/commands which can help to track the problem:

  • netstat -ln | grep mysql
  • php -r «phpinfo();» | grep mysql
  • php -i | grep mysql
  • Use XDebug with xdebug.show_exception_trace=1 in your xdebug.ini
  • On OS X try sudo dtruss -fn mysqld , on Linux debug with strace
  • Check permissions on Unix socket: stat $(mysql_config —socket) and if you’ve enough free space ( df -h ).
  • Restart your MySQL.
  • Check net.core.somaxconn .

Источник

Исправление предупреждения PHP: mysqli_real_connect(): (HY000/2002): with WP CLI and MAMP

Favorite

Добавить в избранное

Главное меню » Блог-платформа wordpress » Исправление предупреждения PHP: mysqli_real_connect(): (HY000/2002): with WP CLI and MAMP

Исправление предупреждения PHP: mysqli_real_connect(): (HY000/2002): with WP CLI and MAMP

Э то будет короткий пост, но мы сочли это необходимым, поскольку нам приходилось сталкиваться с этим нестандартным способом, учитывая нашу ситуацию. Мы решили поиграть с WP CLI, но столкнулся с несколькими проблемами конфигурации.

Его было достаточно просто установить, но мы получили ряд ошибок после выполнения следующей команды:

Трассировка стека ошибки началась с чего-то, связанного со следующим сообщением об ошибке, выгруженным PHP:

PHP Warning: mysqli_real_connect(): (HY000/2002): Connection refused in /path/to/wordpress/wp-includes/wp-db.php on line 1531

И затем это закончилось более дружественной, но немного менее полезной ошибкой от WP CLI:

Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or we can’t contact the database server at `127.0.0.1`. This could mean your host’s database server is down.

Мы пол дня возились с локальными базами данных, поэтому решили, что это что-то напортачило. Проверив, что все работает, и мы не поменяли местами порты в MAMP и вышли в Stack Overflow.

Мы нашли несколько ответов, которые объясняют суть проблемы в том, что класс PHP mysqli_real_connect( ) пытается получить доступ к базовому сокету UNIX способом, который не очень хорошо работает с localhost.

Мы не разбирались в том, что на самом деле происходит на системном уровне, так как мы просто хотели более чистый способ начать новую тему. В нескольких ответах предлагается изменить localhost на локальный IP-адрес, такой как 127.0 .0 .1, но это, похоже, не решило проблему полностью, что привело обратно к MAMP и MySQL Workbench.

Основываясь на подробных ответах по переполнению стека, похоже, что класс PHP ожидает, что SQL будет работать на порте по умолчанию, который обычно равен 3306. Поскольку наша версия MAMP по умолчанию использует порт 8889, мы решили, что это может быть проблемой.

В конце концов, вот как выглядит наш wp-config.php, и теперь все работает:

/** MySQL hostname */ define('DB_HOST', '127.0.0.1:8889');

Мы надеемся, что сможем спасти кому-то лишнее время в решении этой проблемы.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

SQLSTATE[HY000] [2002] Connection refused when trying to initiate connection via Dockerfile’s CMD

src/init.php connects with the DB and creates tables the application needs, if they do not already exist. To connect, I use the environment variables like so:

new PDO( "mysql:host=;dbname=", $_ENV['MARIADB_USER'], $_ENV['MARIADB_PASSWORD'], [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ] ); 

And for the first time I docker-compose up , I always get:

SQLSTATE[HY000] [2002] Connection refused .

At the top of the src/init.php script, I can successfully echo out all of the environment variables used in Docker. So they are all defined.

I’m really confused with this, as docker-compose up and the DB connection only work after failing on the first time docker-compose up fails (with the above-mentioned error). When then calling docker-compose down , then do docker-compose up again in the subsequent times, things all work flawlessly. Any idea why this happens?

I’ve been digging a little further, and I noticed that, wehn the mariadb image is built (e.g. when you first run docker-compose up with the above mentioned file contents), I get the above-mentioned error plus the output:

PLEASE REMEMBER TO SET A PASSWORD FOR THE MariaDB root USER

So it seems that, at the moment of the image being built; the MARIADB_ROOT_PASSWORD is for some reason not applied, but aftewards it is, and that that’s the reason for the failed connection?

Currently, I suppose that this is due to this ?:

If there is no database initialized when the container starts, then a default database will be created. While this is the expected behavior, this means that it will not accept incoming connections until such initialization completes. This may cause issues when using automation tools, such as docker-compose, which start several containers simultaneously.

Источник

Читайте также:  Python вывести строку датафрейма
Оцените статью