pdwonline
pdwonline

Reputation: 11

Docker PHP Container Cannot Connect To MariaDB Container

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

(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

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

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)

Upvotes: 1

Views: 1013

Answers (1)

Dolly Aswin
Dolly Aswin

Reputation: 2794

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

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

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

Upvotes: 5

Related Questions