via
via

Reputation: 503

Can not connect mysql with laravel (docker)

I'm very new to laravel and docker and trying to connect mysql to php container(laravel). I thought set right my docker-compose.yml and env file in laravel project.

Also, I can connect to mysql db inside the container.

Here is a error when I did php artisan migrate :

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

Can anyone know what happened?

docker-compose.yml

version: '3'

services:
  php:
    container_name: php
    build: ./docker/php
    volumes:
    - ./myapp/:/var/www


  nginx:
    image: nginx:latest
    container_name: nginx
    ports:
    - 80:80
    volumes:
    - ./myapp/:/var/www
    - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
    depends_on:
    - php

  db:
    image: mysql:8.0
    container_name: db
    environment:
      MYSQL_ROOT_PASSWORD: root1234
      MYSQL_DATABASE: myapp
      MYSQL_USER: docker
      MYSQL_PASSWORD: docker
      TZ: 'Asia/Tokyo'
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    ports:
    - 3306:3306

env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=docker
DB_PASSWORD=docker


Upvotes: 3

Views: 9084

Answers (2)

via
via

Reputation: 503

finally this problem is solved. I changed .env DB_HOST=127.0.0.1 to DB_HOST=db then it's work!!

" DB_HOST= service name of mysql container on docker-compose.yml "

this time my mysql container name is db, so needed to DB_HOST to be db.

Upvotes: 8

Kurt Friars
Kurt Friars

Reputation: 3764

You are running mysql 8, there are considerations for the authentication mechanism. Try adding the following to your mysql container's command:

--default-authentication-plugin=mysql_native_password

MySQL version 8.0.4 has changed the default authentication mechanism from mysql_native_password to caching_sha2_password. The issue is that most clients have not implemented the ability to authenticate via this mechanism yet. In the case of Laravel, this is dependent upon PHP, and PHP only began supporting this in v7.4.

I personally have not tried to configure this in one of my projects yet, and am unsure if Laravel supports this "out of the box" yet.

Upvotes: 1

Related Questions