I have created and linked php-apache container with MYSQL container. But when I try to establish connection using PDO from a php file I got the error. Does anybody know how it could be fixed ? Thanks.
PDO error:
Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/html/index.php:3 Stack trace: #0 /var/www/html/index.php(3): PDO->__construct('mysql:host=mysq...', 'root', 'root') #1 {main} Next PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/html/index.php:3 Stack trace: #0 /var/www/html/index.php(3): PDO->__construct('mysql:host=mysq...', 'root', 'root') #1 {main} thrown in /var/www/html/index.php on line 3
My directory structure:
.
├── mysql
├── php
| └── Dockerfile
├── src
| └── index.php
└── docker-compose.yml
Content of my index.php:
$connection = new PDO('mysql:host=mysql-db,dbname=app', 'root', 'root');
PHP Dockerfile:
FROM php:7.3.3-apache
RUN docker-php-ext-install -j$(nproc) pdo_mysql
docker-compose.yml:
version: '3'
services:
apache-php:
build:
./php
volumes:
- ./src:/var/www/html
ports:
- "8080:80"
depends_on:
- mysql-db
links:
- mysql-db
mysql-db:
image: mysql:5.7
ports:
- "3306:3306"
volumes:
- /mysql:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: app
networks: - app-networkto link them together in version 3.defaultnetwork for you; you don't need to manually declare one. Thelinks:are unnecessary too.