我刚遇到
PDOException: SQLSTATE[HY000] [2002] Connection refused in /var/www/html/inc/config/db.php on line 11
一开始我以为这与mysql服务器有关,但是经过数小时的尝试和错误,我发现如果使用mysqli_connect根本没有错误,那么错误就是来自PDO
$conn = new PDO("mysql:host=127.0.0.1;dbname=docker", "root", "tiger");
$conn = mysqli_connect("mysql", "root", "tiger", null);
我还尝试了不同的数据库,甚至尝试了新创建的数据库
有人知道为什么一个人工作而另一个人不工作吗? ?
编辑: 我正在使用docker-compose设置环境。 这是docker-compose.yaml
version: "3"
services:
webserver:
build:
context: ./bin/webserver
container_name: '7.1.x-webserver'
restart: 'always'
ports:
- "80:80"
- "443:443"
links:
- mysql
volumes:
- ${DOCUMENT_ROOT-./www}:/var/www/html
- ./config/php/php.ini:/usr/local/etc/php/php.ini
- ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
- ${LOG_DIR-./logs/apache2}:/var/log/apache2
mysql:
build: ./bin/mysql
container_name: '5.7-mysql'
restart: 'always'
ports:
- "3306:3306"
volumes:
- ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql
- ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql
environment:
MYSQL_ROOT_PASSWORD: tiger
phpmyadmin:
image: phpmyadmin/phpmyadmin
container_name: 'sc-phpmyadmin'
links:
- mysql
environment:
PMA_HOST: mysql
PMA_PORT: 3306
ports:
- '8080:80'
volumes:
- /sessions
redis:
container_name: 'sc-redis'
image: redis:latest
ports:
- "6379:6379"
mongo:
container_name: 'mongodb'
image: mongo:4.0.12-xenial
restart: 'always'
ports:
- "${HOST_MACHINE_MONGO_PORT}:27017"
volumes:
- ${MONGO_DATA_DIR-./data/mongodb}:/data/db
- ${MONGO_LOG_DIR-./logs/mongodb/mongod.log}:/var/log/mongodb/mongod.log
- ${MONGO_CONF-./config/mongodb/mongod.conf}:/etc/mongod.conf
答案 0 :(得分:0)
我发现了连接不起作用的原因,是因为该连接正试图连接到端口8888。当它需要连接到端口8889时。
$conn = new PDO("mysql:host=127.0.0.1;port=8889;dbname=docker", "root", "tiger");
要在端口上查找侦听器,请执行以下操作:
netstat -tln
如果MySQL确实在该端口上侦听,您应该会看到类似以下的行。
tcp 0 0 127.0.0.1:3306 0.0.0.0:*
端口3306是MySql的默认端口。
如果您想知道运行Mysql的本地主机的端口号,可以在MySQL命令行客户端上使用此查询-
SHOW VARIABLES WHERE Variable_name = 'port';
mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port | 3306 |
+---------------+-------+
1 row in set (0.00 sec)
它将为您提供运行MySQL的端口号。