简体   繁体   中英

PHP cannot resolve host without root user to connect a MySQL DB but IP address works

define('DB_HOST', 'masterdb');
define('DB_PORT', '3306');
define('DB_DBNAME', 'example');
define('DB_DRIVER', 'mysql');
define('DB_USERNAME', 'luna');
define('DB_PASSWORD', 'alfa');

I set MySQL connection parameter in the config.php file and try to connect to a MySQL server with it.

cat /etc/hosts
55.55.55.55  masterdb
ping masterdb
55.55.55.55

if I try to connect with MySQL client I can connect it without any problem.

mysql -h masterdb --port  3306 -uluna -p

When I try to call the page from a browser

curl "192.168.1.1/login.php"

array(2) {
  ["message"]=>
  string(43) "SQLSTATE[HY000] [2002] Connection timed out"

but if I change the parameters to use the IP address it works.

define('DB_HOST', '55.55.55.55');

curl "192.168.1.1/login.php"

connection success!!!


MYSQL

show global variables like '%resolve%';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| skip_name_resolve | ON    |
+-------------------+-------+

Is there any php.ini setting for it?

Finally, I understood the reason why it is not working but I could not find the solutions yet.

When I run php with "root" user it can connect resolve the host and give success but if I use php-fpm user (nginx, nobody) it fails

sudo -u nginx  /usr/bin/php70 /var/www/html/abc.com/test.php
fails
sudo -u root  /usr/bin/php70 /var/www/html/abc.com/test.php
pass

chmod 644 /etc/hosts

is the answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM