

Macでlaravel,vue.js,docker（ローカルではdockerにnginxを使用）を使用してローカルでWEBアプリを制作しています。.envの設定がおかしいからだとは思いますが、dbとして使用しているローカルのmysqlに繋がらず、そのために
`php artisan migrate`
がエラーとなって詰まってしまっています。どこの設定が間違っているためにmysqlに繋がらないのかを知りたいのですがよろしくお願いします。

### 追記  
マルチポストしていることを説明し忘れました。内容は全く同じですが追記しておきたいと思います。  
<https://teratail.com/questions/dudp4gwhsdoz12>

### エラー

[code]

    root@8be8ddaa6767:/var/www/html# 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 = sample and table_name = migrations and table_type = 'BASE TABLE')
    
      at /var/www/html/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|         }
        673| 
    
      Exception trace:
    
      1   PDOException::("PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known")
          /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
    
      2   PDO::__construct("mysql:host=db;port=3306;dbname=sample", "hoge", "777", [])
          /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
    
      Please use the argument -v to see more details.
    
[/code]

### 追記

コメントで助言されたのを試したところプロセスがうまく実行できていないことまでわかりました。

[code]

    % docker-compose ps
    NAME                COMMAND                  SERVICE             STATUS              PORTS
    portfolio-app-1     "docker-php-entrypoi…"   app                 running             9000/tcp
    portfolio-db-1      "docker-entrypoint.s…"   db                  exited (1)          
    portfolio-web-1     "/docker-entrypoint.…"   web                 running             0.0.0.0:80->80/tcp
    
[/code]

### 追記２

% docker-compose logs db の結果、'utf8mb4_0900_ai_ci'がおかしいとのことです。

[code]

    % docker-compose logs db
    portfolio-db-1  | 2022-03-05 10:29:56+09:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.37-1debian10 started.
    portfolio-db-1  | 2022-03-05 10:29:57+09:00 [ERROR] [Entrypoint]: mysqld failed while attempting to check config
    portfolio-db-1  |   command was: mysqld --verbose --help --log-bin-index=/tmp/tmp.Ef2AJ4XEgw
    portfolio-db-1  |   2022-03-05T10:29:57.143207+09:00 0 [ERROR] Unknown collation: 'utf8mb4_0900_ai_ci'
    portfolio-db-1  | 2022-03-05T10:29:57.148263+09:00 0 [ERROR] Aborting
    masa@MasaakinoMacBook-Air portfolio % 
    
    
    
    docker/mysql/my.cnfの部分にこの記述、 'utf8mb4_0900_ai_ci'　があります
    
    portfolio/docker/mysql/my.cnf
    
    [mysqld]
    user=mysql
    character_set_server = utf8mb4
    //この部分
    collation_server = utf8mb4_0900_ai_ci
    
    # timezone
    default-time-zone = SYSTEM
    log_timestamps = SYSTEM
    
    # Error Log
    log-error = mysql-error.log
    
    # Slow Query Log
    slow_query_log = 1
    slow_query_log_file = mysql-slow.log
    long_query_time = 1.0
    log_queries_not_using_indexes = 0
    
    # General Log
    general_log = 1
    general_log_file = mysql-general.log
    
    [mysql]
    default-character-set = utf8mb4
    
    [client]
    default-character-set = utf8mb4
    
[/code]

またthinkerで環境変数を確認したところ一部反映されてないようでここにも原因がありそうです。

[code]

    masa@MasaakinoMacBook-Air portfolio %  docker-compose exec app bash  
    root@7b0ccf8be086:/var/www/html# php artisan tinker
    Psy Shell v0.11.1 (PHP 7.4.1 — cli) by Justin Hileman
    >>>  env('DB_HOST');
    => "db"
    >>> env('WEB_PORT');
    => null
    >>> env('DB_PORT');
    => "3306"
    >>> env('DB_HOSTURL');
    => null
    >>> env('DB_NAME');
    => null
    >>> env('DB_USER');
    => null
    >>> env('DB_PASSWORD');
    => "777"
    >>> env('DB_ROOT_PASSWORD');
    => null
    >>> 
    
[/code]

バージョン  
php: 7.4.1  
laravel: 6.20.  
MySQL version: 8.0.28

docker, docker-compose.yml は以下のページを参考に利用。

[絶対に失敗しないDockerでLaravel+Vueの実行環境（LEMP環境）を構築する方法〜前編〜](https://qiita.com/shimotaroo/items/29f7878b01ee4b99b951)

[code]

    portfolio($docker-compose up -dをここで起動)
    ├─ docker
    │    ├─ php
    │    │   └─ Dockerfile
    │    │   └─ php.ini
    │    ├─ nginx
    │    │    └─ Dockerfile
    │    │    └─ default.conf
    │    └─ mysql
    │         └─ Dockerfile
    │         └─ my.cnf
    │
    ├─ src(laravelのapp、config,resousesや.env等が入っています)
    │    
    │ 
    │─ .env(下)
    │─ .gitignore   
    └─ docker-compose.yml(下)
    
[/code]

portfolio/.env

[code]

    WEB_PORT=80
    DB_PORT=3306
    //docker-compose.yml内のdb
    DB_HOSTURL=db
    DB_NAME=sample
    DB_USER=hoge
    DB_PASSWORD=777
    DB_ROOT_PASSWORD=secret
    
[/code]

portfolio/src/.env

[code]

    APP_NAME=docker-laravel-vue
    APP_ENV=local
    APP_KEY=省略
    APP_DEBUG=true
    APP_URL=127.0.0.1
    
    LOG_CHANNEL=stack
    
    DB_CONNECTION=mysql
    DB_HOST=db
    DB_PORT=3306
    DB_DATABASE=sample
    
[/code]

docker-compose.yml

[code]

    # Composeファイルのバージョン
    version: '3.8'
    
    volumes:
      mysql-volume:
    
    services:
      app:
        build:
          context: .
          dockerfile: ./docker/php/Dockerfile
        volumes:
          - ./src/:/var/www/html
        environment:
          - DB_CONNECTION=mysql
          - DB_HOST=${DB_HOSTURL}
          - DB_PORT=3306
          - DB_DATABASE=${DB_NAME}
          - DB_USERNAME=${DB_USER}
          - DB_PASSWORD=${DB_PASSWORD}
    
    # web_serverでも可
      web:
        build:
          context: .
          dockerfile: ./docker/nginx/Dockerfile
        ports:
          - ${WEB_PORT}:80
        depends_on:
          - app
        volumes:
          - ./src/:/var/www/html
    
      db:
        build:
          context: .
          dockerfile: ./docker/mysql/Dockerfile
        ports:
          - ${DB_PORT}:3306
        environment:
          MYSQL_DATABASE: ${DB_NAME}
          MYSQL_USER: ${DB_USER}
          MYSQL_PASSWORD: ${DB_PASSWORD}
          MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
          TZ: 'Asia/Tokyo'
        volumes:
          - mysql-volume:/var/lib/mysql      
    
[/code]

追記  
src/config/database.php

[code]

    'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    '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'),
    ]) : [],
    ],
    
    
[/code]

ターミナルに打ち込んだ時に得られる情報

localのmysql詳細

[code]

    masa@MasaakinoMacBook-Air portfolio % pwd
    /Users/masa/Desktop/portfolio
    
    masa@MasaakinoMacBook-Air portfolio % mysql -u hoge -p sample;
    Enter password: 
    //『777』を入力
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 27
    Server version: 8.0.28 Homebrew
    
    Copyright (c) 2000, 2022, Oracle and/or its affiliates.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    
    mysql> select user( );
    +----------------+
    | user( )        |
    +----------------+
    | hoge@localhost |
    +----------------+
    1 row in set (0.00 sec)
    
    mysql> show databases;
    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | sample             |
    +--------------------+
    2 rows in set (0.01 sec)
    
    mysql> SELECT DATABASE();
    +------------+
    | DATABASE() |
    +------------+
    | sample     |
    +------------+
    1 row in set (0.00 sec)
    
    
    mysql> use sample;
    Database changed
    mysql> SELECT DATABASE();
    +------------+
    | DATABASE() |
    +------------+
    | sample     |
    +------------+
    1 row in set (0.00 sec)
    
    mysql> exit
    Bye
    
    masa@MasaakinoMacBook-Air portfolio % mysql -u root -p             
    Enter password: 
    //『secret』を入力
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 30
    Server version: 8.0.28 Homebrew
    
    Copyright (c) 2000, 2022, Oracle and/or its affiliates.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    
    mysql> 
    
[/code]

実際の `php artisan migrate` がうまく行かない部分の詳細

[code]

    masa@MasaakinoMacBook-Air portfolio % mysql.server restart 
    Shutting down MySQL
    . SUCCESS! 
    Starting MySQL
    .. SUCCESS! 
    masa@MasaakinoMacBook-Air portfolio % docker-compose down          
    [+] Running 4/4
     ⠿ Container portfolio-db-1   Removed                                                                                                                                                                  0.1s
     ⠿ Container portfolio-web-1  Removed                                                                                                                                                                  0.3s
     ⠿ Container portfolio-app-1  Removed                                                                                                                                                                  0.3s
     ⠿ Network portfolio_default  Removed                                                                                                                                                                  0.1s
    masa@MasaakinoMacBook-Air portfolio %  docker builder prune &  docker volume prune
    [1] 17257
    WARNING! This will remove all local volumes not used by at least one container.
    Are you sure you want to continue? [y/N] WARNING! This will remove all dangling build cache. Are you sure you want to continue? [y/N] 
    Total reclaimed space: 0B
    masa@MasaakinoMacBook-Air portfolio % docker-compose up -d                       
    [+] Running 4/4
     ⠿ Network portfolio_default  Created                                                                                                                                                                  0.1s
     ⠿ Container portfolio-app-1  Started                                                                                                                                                                  4.3s
     ⠿ Container portfolio-db-1   Started                                                                                                                                                                  1.4s
     ⠿ Container portfolio-web-1  Started                                                                                                                                                                  5.1s
    masa@MasaakinoMacBook-Air portfolio % docker-compose exec app bash    
    root@8be8ddaa6767:/var/www/html# pwd
    /var/www/html
    root@8be8ddaa6767:/var/www/html# ls -a
    .   .editorconfig  .env.testing    .gitignore         .styleci.yml  app  bootstrap  composer.lock  database      package-lock.json  phpunit.xml  resources  server.php  tests   webpack.mix.js
    ..  .env       .gitattributes  .phpunit.result.cache  README.md artisan  composer.json  config         node_modules  package.json   public       routes storage     vendor
             
    root@8be8ddaa6767:/var/www/html# php artisan config:cache 
    Configuration cache cleared!
    Configuration cached successfully!
    root@8be8ddaa6767:/var/www/html# php artisan config:clear 
    Configuration cache cleared!
    root@8be8ddaa6767:/var/www/html# php artisan cache:clear 
    Application cache cleared!
    root@8be8ddaa6767:/var/www/html# 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 = sample and table_name = migrations and table_type = 'BASE TABLE')
    
      at /var/www/html/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|         }
        673| 
    
      Exception trace:
    
      1   PDOException::("PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known")
          /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
    
      2   PDO::__construct("mysql:host=db;port=3306;dbname=sample", "hoge", "777", [])
          /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70
    
      Please use the argument -v to see more details.
    
[/code]


CC BY-SA 4.0
2022-03-01T01:42:04.537
86625
2022-03-05T04:17:32.930
2022-03-05T01:34:06.703
51643
51643
question
php macos docker laravel docker-compose
Docker 環境で php artisan migrate がうまく行かない


`docker-compose logs db` の実行結果

[code]

    portfolio-db-1  | 2022-03-05 10:29:56+09:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.37-1debian10 started.
    portfolio-db-1  | 2022-03-05 10:29:57+09:00 [ERROR] [Entrypoint]: mysqld failed while attempting to check config
    portfolio-db-1  |   command was: mysqld --verbose --help --log-bin-index=/tmp/tmp.Ef2AJ4XEgw
    portfolio-db-1  |   2022-03-05T10:29:57.143207+09:00 0 [ERROR] Unknown collation: 'utf8mb4_0900_ai_ci'
    portfolio-db-1  | 2022-03-05T10:29:57.148263+09:00 0 [ERROR] Aborting
    
[/code]

のように 'utf8mb4_0900_ai_ci' でエラーとなるので

[(Resolved) Unknown collation:
utf8mb4_0900_ai_ci](https://tecadmin.net/resolved-unknown-collation-
utf8mb4_0900_ai_ci/)

のサイトを参考にdocker内を  
COLLATION を'utf8_general_ci'  
CHARACTER を'utf8'  
に変更したところ

（docker/mysql/my.cnfの部分にこの記述、 'utf8mb4_0900_ai_ci' があるのでコードを載せておきたいと思います↓）

portfolio/docker/mysql/my.cnf（元々）

[code]

    [mysqld]
    user=mysql
    character_set_server = utf8mb4
    
    collation_server = utf8mb4_0900_ai_ci
    
    # timezone
    default-time-zone = SYSTEM
    log_timestamps = SYSTEM
    
    # Error Log
    log-error = mysql-error.log
    
    # Slow Query Log
    slow_query_log = 1
    slow_query_log_file = mysql-slow.log
    long_query_time = 1.0
    log_queries_not_using_indexes = 0
    
    # General Log
    general_log = 1
    general_log_file = mysql-general.log
    
    [mysql]
    default-character-set = utf8mb4
    
    [client]
    default-character-set = utf8mb4
    
[/code]

改めて `docker-compose logs db` を実行した結果、以下のようにエラーメッセージが変わりました。

[code]

    masa@MasaakinoMacBook-Air portfolio % 
    portfolio-db-1  | 2022-03-05 10:58:18+09:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.37-1debian10 started.
    portfolio-db-1  | 2022-03-05 10:58:18+09:00 [ERROR] [Entrypoint]: mysqld failed while attempting to check config
    portfolio-db-1  |   command was: mysqld --verbose --help --log-bin-index=/tmp/tmp.u6hnMzU23j
    portfolio-db-1  |   2022-03-05T10:58:18.873878+09:00 0 [ERROR] COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'utf8mb4'
    portfolio-db-1  | 2022-03-05T10:58:18.876518+09:00 0 [ERROR] Aborting
    
[/code]

'utf8_general_ci' は CHARACTER 'utf8mb4' に対して有効でないため  
laravel内、およびdocker内の全てを  
COLLATION を'utf8_general_ci'  
CHARACTER を'utf8'  
に統一すると `php artisan migrate` が通りました。解決できました。ありがとうございました！‍♂️


CC BY-SA 4.0
2022-03-05T02:25:57.143
86692
2022-03-05T04:17:32.930
2022-03-05T04:17:32.930
3060
51643
86625
answer