Docker撰写与PHP,MySQL,nginx连接问题

我有问题连接到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 

PHPtesting脚本:

 <?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 

我的代码有什么问题? 因为我认为这应该没问题

如果有人有更好的解决scheme谢谢你的帮助。

更改$servername = "localhost";$servername = "mysql"; 。 您的MySQL服务不在您的Web服务器容器的本地主机上。 您应该使用服务的名称