Mr.Moe Mr.Moe - 1 year ago 100
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:

image: tutorial/nginx
- "8080:80"
- ./src:/var/www
- ./src/vhost.conf:/etc/nginx/sites-enabled/vhost.conf
- php
image: nmcteam/php56
- ./src/php-fpm.conf:/etc/php5/fpm/php-fpm.conf
- ./src:/var/www
- db
image: sameersbn/mysql
- /var/lib/mysql
- 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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download