0

The application is hosted in a docker container locally on my machine as I am working on the app. The php artisan migrate command is working fine. The problem occurs when I try to load the content onto a web page using any of the Models.

Explanation below:

The Env content:

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

The migration command works.

php artisan migrate

But, when I try to display the data on a page:

public function index(){
    return App\Models\User::all();
}

Laravel says:

SQLSTATE[HY000] [2002] Connection refused

My docker-compose.yml content for mysql:

services:
    mysql:
        image: 'mysql/mysql-server:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ROOT_HOST: "%"
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
        volumes:
            - 'sail-mysql:/var/lib/mysql'
            - './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
        networks:
            - sail
        healthcheck:
            test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
            retries: 3
            timeout: 5s

When I change DB_HOST to the name of the container;

DB_HOST=mysql

Laravel starts to display the data, but php artisan migrate does not work. How it tries to connect to it:

PDO::__construct("mysql:host=mysql;port=3306;dbname=my_db", "root", "", [])

Then fails:

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mysql failed: No such host is known.  (SQL: SHOW FULL TABLES WHERE table_type = 'BASE TABLE')

I need to understand why it is doing so, and how I can resolve this problem. I would also like to know if this will have the same problem when I deploy the application on production.

Thank you.

sheikhamir
  • 17
  • 4
  • `DB_HOST=localhost` or 127.0.0.1, Did you try that? – DreamBold Jan 04 '23 at 07:39
  • Yes, I tried `DB_HOST=localhost`, it shows the host is not found. I tried `DB_HOST=127.0.0.1`, only migration starts working, but the data still can not be loaded onto the web-page. – sheikhamir Jan 04 '23 at 07:47
  • So `DB_HOST=127.0.0.1` is working in your case. For the data not displaying on the webpage, you need to check some other things in Lavarel – DreamBold Jan 04 '23 at 07:50
  • Don't you see the data on the pages after the migration is completed?? – DreamBold Jan 04 '23 at 07:50
  • The data is displayed if I change `DB_HOST=mysql` and then the `php artisan migrate` says `Connection refused` – sheikhamir Jan 04 '23 at 08:28

1 Answers1

0

I found the solution changing in .env file:

DB_PORT=mysql

to:

DB_PORT=host.docker.internal

Source: Laravel Sail Refusing MySQL connection

glcis
  • 1