6
1

More than 3 years have passed since last update.

Dockerのコンテナ内でmigrateを実行した際の「 failed: Name or service not known」に関して

Last updated at Posted at 2020-02-03

DockerでLaravelの環境構築をしてコンテナないで、php artisan migrateを実行すると下記のエラーが発生したので、解決策を忘備録として残しておきます。

エラー内容

root@a65fb3be52e4:/var/www# php artisan migrate

   Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (SQL: select * from information_schema.tables where table_schema = todos_app and table_name = migrations and table_type = 'BASE TABLE')

  at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669
    665| // If an exception occurs when attempting to run a query, we'll format the error
    666| // message to include the bindings with SQL, which will make this exception a
    667| // lot more helpful to the developer instead of just the database's errors.
    668| catch (Exception $e) {
  > 669|  throw new QueryException(
    670|  $query, $this->prepareBindings($bindings), $e
    671|  );
    672| }

  Exception trace:

  1   PDOException::("PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known")
      /var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

  2   PDO::__construct("mysql:host=mysql;port=3306;dbname=todos_app", "root", "", [])
      /var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

  Please use the argument -v to see more details.

failed: Name or service not known と言われているので設定ファイル内が怪しいということで確認してみることに。

各種設定ファイル

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=todos_app
DB_USERNAME=root
DB_PASSWORD=root
docker-composer.yml
  db:
    image: mysql:5.7
    container_name: db-host_2
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: todos_app
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      TZ: 'Asia/Tokyo'
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    volumes:
      - ./docker/db/data:/var/lib/mysql
      - ./docker/db/my.cnf:/etc/mysql/conf.d/my.cnf
      - ./docker/db/sql:/docker-entrypoint-initdb.d
    ports:
      - 3306:3306

.envファイル内で設定しているDB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD はdocker-compose.ymlで設定しているものと同じなので問題はなさそう。。

と思っていたのですが、こちらの記事によると、DB_HOSTはIPアドレスではなくて、service名を指定するとのことでした。

そのため.envファイルを下記に修正したら、無事にmigrateが実行されました。

.env
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=todos_app
DB_USERNAME=root
DB_PASSWORD=root
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1