LoginSignup
lg_chouroutv
@lg_chouroutv

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Laravel でDB接続エラー

自分では開発環境を作ったことないレベルのプログラマーです。

Laravelでローカル開発環境を始めて作っているところで データベース接続エラーが出てしまい、修正方法が分からず質問させてください。

開発環境
PHP : 8.1.17
Docker : 24.0.2
Laravel : 10.15.0
MYSQL : 8.0.33

PC : iMac
OS : Ventura 13.4.1
Visuai Studio Code : 1.81.0

DockerでLaravelをインストールし、phpMyAdminもローカル接続できる状態まで来ております。
Modelやmigrationファイルを作って、いざマイグレーションしようとしたところ

php artisan migrate

以下のエラーが発生しました。

SQLSTATE[HY000] [2002] Connection refused (Connection: mysql, SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations and table_type = 'BASE TABLE')

 at vendor/laravel/frameworkIlluminate/Database/Connection.php:795
   791▕         // If an exception occurs when attempting to run a query, we'll format the error
   792▕         // message to include the bindings with SQL, which will make this exception a
   793▕         // lot more helpful to the developer instead of just the database's errors.
   794▕         catch (Exception $e) {
 ➜ 795▕             throw new QueryException(
   796▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
   797▕             );
   798▕         }
   799▕     }
  
     +38 vendor frames 

 39  artisan:35
     Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

データベース接続エラーだと思うのですが、どこを修正すればいいか分からず困っています。
自分なりに以下のファイルのどこかじゃないかと思う部分を記載します。
検討違いだったらすみません。
なにかヒントあれば教えて頂きたいです。よろしくお願い致します。

docker-compose.yml

mysql:
    image: mysql:8.0.33
    command: --max_allowed_packet=32505856
    container_name: "mysql"
    volumes:
      - ./docker/mysql:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=mysql
    ports:
      - 3306:3306
  
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    depends_on:
      - mysql
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOSTS=mysql
      - PMA_USER=root
      - PMA_PASSWORD=root
    ports:
      - "3000:80"
    volumes:
      - ./docker/phpmyadmin/sessions:/sessions

.env

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

database.php

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            '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'),
            ]) : [],
        ],
0

3Answer

Laravel は触ったこともないのでハズレかもしれませんが・・・

もし、エラーメッセージが 795 行目の throw new QueryException の結果であれば、例外を catch しないで実際の例外が何でそのエラーメッセージがどう言うものかを見てはいかがですか? そこに解決のためのヒントが見つかるかも知れません。

0

Comments

  1. @lg_chouroutv

    Questioner

    ありがとうございます。

Dockerコンテナ間で接続するので、DB_HOST127.0.0.1ではなくサービス名のmysqlではないでしょうか?

0

Comments

  1. @lg_chouroutv

    Questioner

    試してみましたがエラーでした。
    少しエラー文が変わりました。

     Illuminate\Database\QueryException 
    
      SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mysql failed: Name or service not known (Connection: mysql, SQL: select * from information_schema.tables where table_schema = app and table_name = migrations and table_type = 'BASE TABLE')
    
      at vendor/laravel/frameworkIlluminate/Database/Connection.php:795
        791▕         // If an exception occurs when attempting to run a query, we'll format the error
        792▕         // message to include the bindings with SQL, which will make this exception a
        793▕         // lot more helpful to the developer instead of just the database's errors.
        794▕         catch (Exception $e) {
      ➜ 795▕             throw new QueryException(
        796▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
        797▕             );
        798▕         }
        799▕     }
    
          +38 vendor frames 
    
      39  artisan:35
          Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
    
    

Comments

  1. @lg_chouroutv

    Questioner

    試してみましたがエラーでした。
    少しエラー文が変わりました。

       Illuminate\Database\QueryException 
    
      SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mysql failed: Name or service not known (Connection: mysql, SQL: select * from information_schema.tables where table_schema = app and table_name = migrations and table_type = 'BASE TABLE')
    
      at vendor/laravel/frameworkIlluminate/Database/Connection.php:795
        791▕         // If an exception occurs when attempting to run a query, we'll format the error
        792▕         // message to include the bindings with SQL, which will make this exception a
        793▕         // lot more helpful to the developer instead of just the database's errors.
        794▕         catch (Exception $e) {
      ➜ 795▕             throw new QueryException(
        796▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
        797▕             );
        798▕         }
        799▕     }
    
          +38 vendor frames 
    
      39  artisan:35
          Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
    

Your answer might help someone💌