Mysql on docker gives "Connection refused" error

Viewed 2575

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?

2 Answers

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

I tried my mysql IP before. When I got a connection refused error on DBeaver, it gave me an IP address of 17.23.0.1. I thought this was my mysql IP and tried it this way. I wanted to look at my container IPs and tried the following command. The IP that came out was different. With this IP, I was finally able to run the php artisan migrate code.

docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)

Later I realized that it was unnecessary. If I give the container name directly, my problem is handled more neatly.

DB_HOST=db
Related