我遇到连接MySQL容器的问题。
搬运工-compose.yml
version: '2'
services:
mysql:
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: JoeyW#1999
MYSQL_DATABASE: wiput
MYSQL_USER: web
MYSQL_PASSWORD: Web#1234
volumes:
- ./mysql:/var/lib/mysql
networks:
- code-network
php:
image: wiput1999/php:latest
volumes:
- ./code:/code
networks:
- code-network
nginx:
image: nginx:latest
ports:
- "80:80"
- "443:443"
volumes:
- ./code:/code
- ./site.conf:/etc/nginx/conf.d/default.conf
- /etc/letsencrypt:/etc/letsencrypt
networks:
- code-network
networks:
code-network:
driver: bridge
PHP测试脚本:
<?php
$servername = "localhost";
$username = "root";
$password = "JoeyW#1999";
try {
$conn = new PDO("mysql:host=$servername;dbname=wiput", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
这个脚本响应我:
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
我的代码出了什么问题?因为我觉得它应该没问题
如果有人有更好的解决方案,谢谢你的帮助。
答案 0 :(得分:5)
将$servername = "localhost";
更改为$servername = "mysql";
。您的mysql服务不在您的Web服务器容器的localhost上。您应该使用服务名称