I’m trying to connect to containerized MySQL DB from PHP container although all the containers on the same network, the issue is I keep getting Connection failed: invalid data source name
when I hit http://localhost:8080/dbTest.php
although I’ve checked that the credential is correct and the demo DB exists using mysql -u root -p
I see this message in mysql log mbind: Operation not permitted could be related?
Thanks
Apache Dockerfile
FROM httpd:latest
RUN apt-get update
RUN apt-get upgrade
COPY demo.apache.conf /usr/local/apache2/conf/demo.apache.conf
RUN echo "Include /usr/local/apache2/conf/demo.apache.conf" >> /usr/local/apache2/conf/httpd.conf
cmd: docker run -p 8080:80/tcp -v /home/hmalabeh/tutorial/docker/lamp/files/:/usr/local/apache2/htdocs/ –link=php –name apache –network backend -i 8f704f51962d
PHP Dockerfile
FROM php:7.2.7-fpm-alpine3.7
RUN docker-php-ext-install mysqli
RUN docker-php-ext-enable mysqli
RUN docker-php-ext-install pdo pdo_mysql
EXPOSE 9000
cmd: docker run -p 9000:9000 -v /home/hmalabeh/tutorial/docker/lamp/files/:/var/www/html/ –name php –network backend -i 1cc049496b03
MySQL Dockerfile
FROM mysql:latest
RUN apt-get update
RUN apt-get upgrade
ENV MYSQL_ROOT_PASSWORD=root
cmd: docker run -p 3306:3306 -p 33060:33060 –name mysql –network backend –link=php -i 7bb7d4985301
dbTest.php
<?php
class DBConnect
{
private $dsn = "mysql:dbname=demo;host=127.0.0.1;port=3306;";
private $dbUsername = "root";
private $dbPassword = "root";
private $conn;
public function connect()
{
try {
echo 'Attempt Connection. ';
$this->conn = new PDO($dsn, $dbUsername, $dbPassword);
echo 'Connected successfully. ';
} catch (PDOException $exception) {
echo 'Connection failed: ' . $exception->getMessage();
}
return $this->conn;
}
}
$co = new DBConnect();
$co->connect();
?>
My running containers
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9639160c0824 8f704f51962d "httpd-foreground" 2 hours ago Up 2 hours 0.0.0.0:8080->80/tcp apache
38e630a9cb01 7bb7d4985301 "docker-entrypoint.s…" 2 hours ago Up 2 hours 0.0.0.0:3306->3306/tcp, 0.0.0.0:33060->33060/tcp mysql
c7f6e8db26a9 1cc049496b03 "docker-php-entrypoi…" 2 hours ago Up 2 hours 0.0.0.0:9000->9000/tcp php
3
Answers
I forget to add
$->this
before the variable, the code should be like below.Add a
host
to the DSN using the name of the container since they are in the same network:Reference
have you enabled remote access in mySql?
replace:
bind-address= 127.0.0.1
for
bind-address= 0.0.0.0