Docker Connecting PHP container to MySQL

John Mack picture John Mack · Jul 9, 2017 · Viewed 8.8k times · Source

I have two containers, a apache-php container, and a mysql db container. I am trying to get my php script to query my sql database. I am however receiving the following errors;

Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known

AND

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory

when toggling the host address, i think i am missing something fundamental to docker and this is driving my crazy.

My docker compose looks like;

version: '2'

services:

    applications:
      image: tianon/true
      volumes:
        - /var/www/test:/var/www/html

    mysql_store:
      image: tianon/true
      volumes:
        - /var/www/test/mysql:/var/lib/mysql

    apache2:
      build:
        context: ./apache2
      volumes_from:
        - applications
      ports:
        - "80:80"
      depends_on:
       - mysql
      links:
        - mysql
    mysql:
      build:
        context: ./mysql
        volumes_from:
          - mysql_store
      environment:
        - MYSQL_DATABASE=testapp
        - MYSQL_USER=johnm
        - MYSQL_PASSWORD=johnm
        - MYSQL_ROOT_PASSWORD=secret
      volumes:
        - ./mysql/save:/var/lib/mysql
      ports:
        - "3306:3306"

my mysql dockerfile looks like

FROM mysql:8

MAINTAINER Mahmoud Zalt <[email protected]>

#####################################
# Set Timezone
#####################################

ARG TZ=UTC
ENV TZ ${TZ}
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

RUN chown -R mysql:root /var/lib/mysql/

ADD my.cnf /etc/mysql/conf.d/my.cnf

CMD ["mysqld"]

EXPOSE 3306

my apache dockerfile looks like;

FROM php:7.0-apache
#COPY ./src/ /var/www/html/i
#RUN apt-get update && add-apt-repository ppa:ondrej/php && apt-get update && apt-get install php7.0-mysql
RUN apt-get update && apt-get install -y \
    && docker-php-ext-install pdo pdo_mysql \
    && docker-php-ext-enable pdo pdo_mysql

and finally my index.php looks like

<?php
    $db = new PDO('mysql:host=localhost;port=3306;dbname=testapp', 'root', 'secret');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    var_dump($db->query('SELECT * from users'));

For my database host i have tried "db", "localhost" and "127.0.0.1".

Any help on this will be greatly appreciated!

Answer

Robert picture Robert · Jul 9, 2017

What you need to use as DNS name is the service name: mysql:

 $db = new PDO('mysql:host=mysql;port=3306;dbname=testapp', 'root', 'secret');

Because you named as so the MySQL compose service:

    mysql:
      build:
        context: ./mysql
...