gpt4 book ai didi

php - Docker Compose 与 PHP、MySQL、nginx 连接问题

转载 作者:可可西里 更新时间:2023-11-01 07:05:04 24 4
gpt4 key购买 nike

我在连接到 MySQL 容器时遇到问题。

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

我的代码有什么问题?因为我觉得应该没问题

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

最佳答案

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

关于php - Docker Compose 与 PHP、MySQL、nginx 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com