title: Docker Connecting PHP container to MySQL
body: <p>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;</p>
  
  <pre><code>Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known
  </code></pre>
  
  <p>AND </p>
  
  <pre><code>Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory
  </code></pre>
  
  <p>when toggling the host address, i think i am missing something fundamental to docker and this is driving my crazy.</p>
  
  <p>My docker compose looks like;</p>
  
  <pre><code>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"
  </code></pre>
  
  <p>my mysql dockerfile looks like</p>
  
  <pre><code>FROM mysql:8
  
  MAINTAINER Mahmoud Zalt &lt;mahmoud@zalt.me&gt;
  
  #####################################
  # Set Timezone
  #####################################
  
  ARG TZ=UTC
  ENV TZ ${TZ}
  RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime &amp;&amp; echo $TZ &gt; /etc/timezone
  
  RUN chown -R mysql:root /var/lib/mysql/
  
  ADD my.cnf /etc/mysql/conf.d/my.cnf
  
  CMD ["mysqld"]
  
  EXPOSE 3306
  </code></pre>
  
  <p>my apache dockerfile looks like;</p>
  
  <pre><code>FROM php:7.0-apache
  #COPY ./src/ /var/www/html/i
  #RUN apt-get update &amp;&amp; add-apt-repository ppa:ondrej/php &amp;&amp; apt-get update &amp;&amp; apt-get install php7.0-mysql
  RUN apt-get update &amp;&amp; apt-get install -y \
      &amp;&amp; docker-php-ext-install pdo pdo_mysql \
      &amp;&amp; docker-php-ext-enable pdo pdo_mysql
  </code></pre>
  
  <p>and finally my index.php looks like</p>
  
  <pre><code>&lt;?php
      $db = new PDO('mysql:host=localhost;port=3306;dbname=testapp', 'root', 'secret');
      $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $db-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  
      var_dump($db-&gt;query('SELECT * from users'));
  </code></pre>
  
  <p>For my database host i have tried "db", "localhost" and "127.0.0.1".</p>
  
  <p>Any help on this will be greatly appreciated!</p>