Mr.Moe Mr.Moe - 3 months ago 15
MySQL Question

Can't connect to MySQL docker container created via docker-compose

I want to get started with docker and created a simple container environment with an nginx container, a PHP-FPM container and a MySQL container.

While the link between the nginx and PHP-FPM container works well I can't seem to link the PHP application server with the database server.

I use docker-compose to minimize the manual terminal work. My docker-compose.yml looks like this:

web:
image: tutorial/nginx
ports:
- "8080:80"
volumes:
- ./src:/var/www
- ./src/vhost.conf:/etc/nginx/sites-enabled/vhost.conf
links:
- php
php:
image: nmcteam/php56
volumes:
- ./src/php-fpm.conf:/etc/php5/fpm/php-fpm.conf
- ./src:/var/www
links:
- db
db:
image: sameersbn/mysql
volumes:
- /var/lib/mysql
environment:
- DB_NAME=demoDb
- DB_USER=demoUser
- DB_PASS=demoPass


While I try to connect to the DB with the following statement:

$db = new \PDO('mysql:host=db;dbname=demoName', 'demoUser', 'demoPass');


The MySQL container itself is working as I can connect to the containers bash and use the MySQL CLI:

mysql> show databases;

+--------------------+
| Database |
+--------------------+
| information_schema |
| demoDb |
| mysql |
| performance_schema |
+--------------------+


I just get a 500 error and can't find a reason why this wouldn't work. Any help or suggestion of what I might have missed is more than appreciated.

Answer

This is not a Docker issue but a code issue:

You have: $db = new \PDO('mysql:host=db;dbname=demoName', 'demoUser', 'demoPass');

It should be: $db = new \PDO('mysql:host=db;port=3306;dbname=demoDb', 'demoUser', 'demoPass');