1

I start with docker, and I want to connect to my database using the PDO driver. But unfortunately, I have an error that appears on my page and I do not know how to solve it. Can you help me please ?

Here is my error:

Fatal error: Uncaught PDOException: PDO :: __ construct (): php_network_getaddresses: getaddrinfo failed: No address associated with hostname

Here is my index.php:

<?php
    $db = new PDO('mysql:host=db:3306;dbname:DockerProject', "root", "root");
?>

Here is my dockerfile:

FROM php:7.2-apache
RUN apt-get update && apt-get install -y libpng-dev libjpeg-dev libpq-dev \
&& rm -rf /var/lib/apt/lists/* \
&& docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr \
&& docker-php-ext-install gd mbstring pdo pdo_mysql pdo_pgsql

Here is my docker-compose.yaml:

version: '3'

services:
  db:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: DockerProject
      MYSQL_USER: devuser
      MYSQL_PASSWORD: devpass
    ports:
      - "3306:3306"
  web:
    image: php_pdo:latest
    container_name: php_web
    depends_on:
      - db
    volumes:
      - ./php/:/var/www/html/
    ports:
      - "8100:80"
    stdin_open: true
    tty: true
  myadmin:
    image: phpmyadmin/phpmyadmin
    ports:
        - "8080:80"
    links:
        - db:db
3
  • port is a separate option in dsn-string. Commented Dec 16, 2018 at 11:34
  • I try host=db:3306 and i have the same error Commented Dec 16, 2018 at 11:39
  • Just host=db; Commented Dec 16, 2018 at 11:43

1 Answer 1

2

Define dsn as

$db = new PDO('mysql:host=db;dbname=DockerProject', "root", "root");

If you need to define a port explicitly, use:

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

Also, not sure why dbname:DockerProject works as correct syntax is dbname=DockerProject.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.