mysqllaraveldocker-composelaravel-8connection-refused

Mysql on docker gives "Connection refused" error


I created my Laravel project with docker-compose. I created a database called fhblog in my local. When I enter the php container and run the php artisan migrate command, I get the following error.

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

I searched for the solution to the problem and followed the people's suggestions, but the error could not be solved.

My .env file

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

My mysql container

  .
  .
  .
  db:
    image: mysql:5.7.22
    container_name: mysql
    restart: unless-stopped
    tty: true
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_USER: root
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: fhblog
      MYSQL_USER: fhblog
      MYSQL_PASSWORD: root
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    volumes:
      - ./docker/mysql/db:/var/lib/mysql
      - ./docker/mysql/my.cnf:/etc/mysql/my.cnf
    networks:
      - app-network
  .
  .
  .

In my research, it was recommended to run the php artisan cache:clear and php artisan config:clear commands, as they can remain in the "cache". These commands did not solve my problem either. Where is the error?


Solution

  • I think you should use the internal ip of mysql instead of container name; login to the mysql container and run bash then type ifconfig probably your ip address is something like this

    172.0.0.23
    

    copy that and paste it in front of

    DB_HOST=
    

    but first of all try using container name as your

    DB_HOST=mysql
    

    or even rename it to something other than mysql

    for example mysql_container

    container_name: mysql_container
    ...
    DB_HOST=mysql_container