Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 425
Mr.Moe Avatar asked May 26 '16 14:05

Mr.Moe


2 Answers

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

like image 52
GHETTO.CHiLD Avatar answered Sep 29 '22 09:09

GHETTO.CHiLD


If you have 0.0.0.0 host for your container with MySql and you want to connect with the database from outside docker (WorkBench or SequelPro), just use your docker-machine IP. Example:

user$ docker-machine ls
NAME      ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER    ERRORS
default   *        virtualbox   Running   tcp://192.168.99.100:2376           v1.12.0

Then your host to MySQL is 192.168.99.100 with proper port e.g. 3306

like image 28
R Picheta Avatar answered Sep 29 '22 07:09

R Picheta