我有遗留的PHP应用程序.它使用mysqli来制作mysql的东西.所以在配置中我有DSN字符串连接到mysql服务.像那样
MySQL的://用户名:密码@ db_hostname / DBNAME
Mysqli返回错误
警告:mysqli :: real_connect():php_network_getaddresses:getaddrinfo failed:名称或服务未知
但是,如果我尝试使用此手动连接
mysqli的:: real_connect( “db_hostname”)
它说警告:mysqli :: real_connect():( HY000 / 1045):用户”’172.21.0.3’拒绝访问(使用密码:否)
real_connect(“user @ db_hostname”),real_connect(“mysql:db_hostname”),real_connect(“mysql:host = db_hostname”)无法解析主机地址.
我做错了什么?
泊坞窗,compose.yml:
version: "3"
services:
nginx:
image: nginx:1.13-alpine
volumes:
- ./docker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./docker/nginx/errors.log:/var/logs/errors.log
- ./docker/nginx/access.log:/var/logs/access.log
- ./:/var/www/html
ports:
- "8081:80"
command: nginx -g "daemon off;"
php:
build:
context: ./docker/
dockerfile: php.Dockerfile
user: "1000"
volumes:
- ./docker/timezone.php.ini:/usr/local/etc/php/conf.d/timezone.php.ini:ro
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
- ./:/var/www/html
db_hostname:
image: mysql:5.5
user: "1000"
environment:
- MYSQL_DATABASE=db
- MYSQL_ROOT_PASSWORD=root
- MYSQL_USER=user
- MYSQL_PASSWORD=user
volumes:
- ./docker/mysql:/var/lib/mysql
- /etc/timezone:/etc/timezone:ro
- /etc/localtime:/etc/localtime:ro
解决方法:
因为你错过了将db容器与php连接起来.当您将db与PHP链接时,可以从PHP的localhost访问它.
这是我修改你的docker-compose文件,因为我喜欢高山到处都是;).我使用adminer并与db链接到verfiy连接而不是代码级别检查.因为我没有你的php docker文件所以我正在创建php:alpine其中包含php7.
version: "3"
services:
nginx:
image: nginx:1.13-alpine
container_name: nginx
ports:
- "8081:80"
command: nginx -g "daemon off;"
db:
image: mysql:5.5
environment:
MYSQL_ROOT_PASSWORD: example
php:
image: php:alpine
container_name: php
tty: true
links:
- db
adminer:
image: adminer
container_name: adminer
ports:
- 8080:8080
links:
- db
然后我在php容器中安装了mysqli
docker exec -it php ash
并在命令下运行
docker-php-ext-install mysqli;
然后创建test.php
这里服务器名称是db.请注意,您的服务器名称将是链接到php的db容器名称.
如果你在php容器中ping db,它将ping数据库容器.
<?php
$servername = "db";
$username = "root";
$password = "example";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
现在在php容器中运行此文件.您可以挂载并运行您的PHP代码,但这是我为测试所做的.我作为root用户尝试过.
php -f test.php
这里是与db连接的adminer