0

I am writing a web using MySQL and PHP. At first, I used phpmyadmin, and now I basically finished the program, and trying to put it into Docker and I am new to Docker. After run docker build -t my-php-app . in terminal, and start the Docker image, I can go to the website, but cannot connect to the database. The error message is:

Failed to connect DB: SQLSTATE[HY000] [2002] No such file or directory

My Dockerfile:

FROM php:8.2-apache
RUN apt-get update && apt-get install -y \
    libzip-dev \
    unzip \
    && docker-php-ext-install zip pdo_mysql
RUN a2enmod rewrite
COPY . /var/www/html
WORKDIR /var/www/html

My docker-compose.yaml:

version: '3.8'
services:
  db:
    container_name: db
    image: mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: ShoppingWebDB
      MYSQL_USER: root
      MYSQL_PASSWORD: root
    ports:
      - "9906:3306"
  php-apache-environment:
    container_name: myweb
    image: php:8.2-apache
    volumes:
      - .:/var/www/html/
    ports:
      - 8000:80
  myweb:
    image: myweb
    hostname: localhost
    ports:
      - '8080:80'
    build:
      dockerfile: Dockerfile
    restart: always
    environment:
      PMA_HOST: db
    depends_on:
      - db
      - php-apache-environment

I think the problem probably due to my docker? But not sure where and how to correct. Could someone help? Thanks!

Emmm
  • 33
  • 4
  • Does this answer your question? [MySQL connection not working: 2002 No such file or directory](https://stackoverflow.com/questions/1676688/mysql-connection-not-working-2002-no-such-file-or-directory) – Georg Richter Jul 26 '23 at 03:21
  • you mean, change the localhost to 127.0.0.1 or real IP? No, I tried, but not work. Besides, when I use MAMP, it all works good. And now I am trying to use docker, and the web just shows cannot connect to db. – Emmm Jul 26 '23 at 03:27
  • 1
    When connecting to the database your app needs to specify `db` as the hostname, not `localhost`. There is no MySQL instance running in the other two containers. – user1191247 Jul 26 '23 at 08:19
  • I change to db now, but it still shows the same bug info. – Emmm Jul 26 '23 at 17:40

0 Answers0