Docker PHP 容器无法连接到 MariaDB 容器 [英] Docker PHP Container Cannot Connect To MariaDB Container

查看:40
本文介绍了Docker PHP 容器无法连接到 MariaDB 容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 docker 使用这些命令在单独的容器中启动 Nginx、PHP 和 mariaDB:

I am using docker to start Nginx, PHP and mariaDB in seperate containers with these commands:

# DB
docker run  --name db -d -p 3306:3306 --restart=always -v /opt/db:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=<pass> -e MYSQL_USER=dbuser -e MYSQL_PASSWORD=<pass> mariadb

# PHP
docker run --name php -p :9000 -d --restart=always --link=db:db -v /www:/data php:fpm

# WEB
docker run --name web -d -p 80:80 --link php --link=db:db -v /www:/data -v /opt/nginx/default.conf:/etc/nginx/conf.d/default.conf nginx:latest

(当然我的密码已经填写)到目前为止一切顺利,有一个旋转的 nginx 在本地运行,我可以看到我的 www 文件夹中的 index.htm 和 phpinfo.php 正确显示在 http://localhost

(of course has my password filled in) So far so good, have a spinning nginx running locally and I can see the index.htm and phpinfo.php in my www folder presented correctly at http://localhost

接下来,我创建了一个包含以下内容的 dbcheck.php 页面:

Next, I created a dbcheck.php page with the following contents:

<?php
$dbh = mysqli_connect('localhost', 'dbuser', '<pass>');
if (!$dbh) {
    die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully to MariaDB database';
mysqli_close($dbh);
?>

结果是 PHP 没有安装 MySQL 扩展.我在做什么错和/或如何安装 MySQL 扩展(以及在哪里)

The result is that PHP does not have the MySQL extension installed. What am I doing wrong and/or how can I install the MySQL extention (and where)

推荐答案

请使用 db 作为主机名,而不是 localhost.所以,代码会是这样的

Please use db for hostname instead of localhost. So, the code will be like this

$dbh = mysqli_connect('db', 'dbuser', '<pass>');

因为您使用此选项 --link=db:db 将 php 容器与 mariadb 容器链接.这意味着您链接到 db 容器并将其命名为 db.所以,php 容器只知道 db 作为 mariadb 容器的主机名

Because you link the php container with mariadb container using this options --link=db:db. It mean you link to db container and name it as db. So, php container just know db as the hostname for mariadb container

这篇关于Docker PHP 容器无法连接到 MariaDB 容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆