Laravel connection to mysql container error docker

I am out of option . going through many solutions nothing worked . It has been asked by many people but nothing earlier solutions worked for me .

.env

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=root

config/database.php

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'db'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', 'root'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

docker-compose.yml

version: "3.7"
services:

  nginx-proxy:
    restart: always
    container_name: nginx-proxy
    image: jwilder/nginx-proxy
    labels:
       com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy: "true"
    networks:
      - intranet
      - csd
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ~/certs:/etc/nginx/certs:ro
      - /etc/nginx/vhost.d
      - /usr/share/nginx/html

  nginx-letsencrypt:
    container_name: nginx-letsencrypt
    image: jrcs/letsencrypt-nginx-proxy-companion
    networks:
      - intranet
    environment:
      - NGINX_PROXY_CONTAINER=jwildernginxproxy
    volumes:
      - ~/certs:/etc/nginx/certs:rw
      - /etc/nginx/vhost.d
      - /usr/share/nginx/html
      - /var/run/docker.sock:/var/run/docker.sock:ro

  

  loan:
    restart: always
    image: loan:latest
    networks:
      - intranet
    container_name: loans
    ports:
      - 8197:80
    volumes:
      - /root/loan/loan/:/var/www/html
    depends_on: 
      - nginx-proxy
      - nginx-letsencrypt

  restore:
    restart: always
    image: restore:latest
    networks:
      - intranet
    container_name: restore_website
    ports:
      - 8196:80
    volumes:
      - /root/restore/app/:/var/www/html
    depends_on: 
      - nginx-proxy
      - nginx-letsencrypt
    environment:
      - VIRTUAL_HOST=www.xxxx.com,xxxx.com
      - LETSENCRYPT_HOST=www.xxxx.com,xxx.com
      - [email protected]

  app:
    build:
      args:
        user: laravel
        uid: 1000
      context: /root/csd/csdpopa-remote
      dockerfile: Dockerfile
    image: csdpopa
    container_name: csdpopa-app
    restart: unless-stopped
    working_dir: /var/www/
    ports:
      - 8999:80
    depends_on: 
      - nginx-proxy
    volumes:
      - /root/csd/csdpopa-remote:/var/www
    networks:
      - csd

  db:
    image: mysql:5.7
    container_name: csd-db
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_USER: ${DB_USERNAME}
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    ports:
      - "3306:3306"
    volumes:
      - ./docker-compose/mysql:/docker-entrypoint-initdb.d
      # - ./docker-compose/mysql:/var/lib/mysql
    depends_on: 
      - nginx-proxy
    networks:
      - csd

volumes: 
  certs:

networks:
  intranet:
  csd:
    driver: bridge

.env #for docker-compose

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=larvel
DB_PASSWORD=root

Error

[2021-04-12 16:03:04] local.ERROR: SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from `permissions`) {"exception":"[object] (Illuminate\Database\QueryException(code: 2002): SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from `permissions`) at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, Doctrine\DBAL\Driver\PDOException(code: 2002): SQLSTATE[HY000] [2002] No such file or directory at /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31, PDOException(code: 2002): SQLSTATE[HY000] [2002] No such file or directory at /var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27)

Able to make connection :

  1. From docker-compose exec db mysql -u root -p laravel
  2. Able to make connection form outside container using datagrip

Things i tried :

  • Tried using docker internal IP _ No joy
  • Tried using direct connection using public IP _ No joy

Hope fellow coder can help me on this

Update Changed image to mariadb

db:
    image: mariadb:10.5.6

Error docker logs

csdpipa-app          | In Connection.php line 664:
csdpipa-app          |
csdpipa-app          |   SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from `permi
csdpipa-app          |   ssions`)
csdpipa-app          |
csdpipa-app          |
csdpipa-app          | In PDOConnection.php line 31:
csdpipa-app          |
csdpipa-app          |   SQLSTATE[HY000] [2002] No such file or directory
csdpipa-app          |
csdpipa-app          |
csdpipa-app          | In PDOConnection.php line 27:
csdpipa-app          |
csdpipa-app          |   SQLSTATE[HY000] [2002] No such file or directory
csdpipa-app          |
csdpipa-app          |

Answer

It all looks good. . Any chance your config was cached ?

php artisan config:clear

php artisan cache:clear

If the above not works.

Try deleting cache if any something you can find cache>config.php

Try these to test you Laravel connection in config>web.php

 try {
        DB::connection()->getPdo();
        if(DB::connection()->getDatabaseName()){
            echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
        }else{
            die("Could not find the database. Please check your configuration.");
        }
    } catch (Exception $e) {
        die("Could not open connection to database server.  Please check your configuration.");
    }

This will give you whether you able to reach DB or not with laravel

Try to switch from this

php artisan serve

Use

php -S 0.0.0.0:8999 -t public/

This might help because if you use artisan serve and make changes to env you must kill the serve and run again.

Try this docker file

FROM php:7.4-fpm

# Arguments defined in docker-compose.yml
ARG user
ARG uid

# Install system dependencies
RUN apt-get update && apt-get install -y 
    git 
    curl 
    libpng-dev 
    libonig-dev 
    libxml2-dev 
    zip 
    unzip

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd

# Get latest Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Create system user to run Composer and Artisan Commands
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && 
    chown -R $user:$user /home/$user

# Set working directory
ADD . /var/www
ADD ./public /var/www/html
WORKDIR /var/www
RUN chmod a+rwx -R /var/www/html
# Expose apache. Use 80 for without HTTPS , for HTTPS use use 443
EXPOSE 8999

USER $user

# if you use `php artisan serve` and make changes to env you must kill the serve and run again.

CMD php -S 0.0.0.0:8999 -t public/

# CMD php artisan serve --host=0.0.0.0 --port=9000