SQLSTATE[HY000] [2002] No such file or directory with php, mysql in docker

dm7nw8vv  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(142)

Using containers in docker, I try to access with php to a database and I get the error "No such file or directory".
docker-compose.yml

version: '3'

services:
  database:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: 12345
      MYSQL_DATABASE: gexpenses
      MYSQL_USER: gexpenses
      MYSQL_PASSWORD: 1234
    ports:
      - "3311:3306"
    volumes:
      - ./bd:/var/lib/mysql:rw
      - ./bd.sql:/docker-entrypoint-initdb.d/bd.sql:ro
  web:
    build: .
    container_name: php_web
    links:
      - database
    volumes:
      - ./local/:/var/www/html/
    ports:
      - "8100:80"
    stdin_open: true
    tty: true

Dockerfile

FROM php:8.0-apache
COPY ./local /usr/src/dst_folder
WORKDIR /usr/src/dst_folder
RUN apt-get update && apt-get install -y \
    libpq-dev \
    && docker-php-ext-install pdo pdo_mysql

my connection in PHP

<?php

$usr = "gexpenses";
$pwd = "1234";

try {
    $pdo = new PDO("mysql:host=localhost;port=3311;dbname=gexpenses", $usr, $pwd);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected succesfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

I tried to create a bridge connection in case it was a connection problem between containers.
I also tried to change from localhost to database in the php host config but it returns "Connection refused".
Another test was to use

docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{{.IPAddress}}{{end}}}' $(docker ps -aq)

return:
/php_web - 172.20.0.3
/database_1 - 172.20.0.2

I have also tried changing localhost to 172.20.0.2 returning "Connection refused".

9jyewag0

9jyewag01#

Please try this you have to create a docker network to connect your containers. The containers must be in the same network to comunicate to echother. If this not work please send the output of docker network inspect web

version: '3'

services:
  database:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: 12345
      MYSQL_DATABASE: gexpenses
      MYSQL_USER: gexpenses
      MYSQL_PASSWORD: 1234
    ports:
      - "3311:3306"
    volumes:
      - ./bd:/var/lib/mysql:rw
      - ./bd.sql:/docker-entrypoint-initdb.d/bd.sql:ro
    networks: web
  web:
    build: .
    container_name: php_web
    links:
      - database
    volumes:
      - ./local/:/var/www/html/
    ports:
      - "8100:80"
    stdin_open: true
    tty: true
    networks: web 
networks:
  web:
    external: false

相关问题