skip to Main Content

I am pretty new to Laravel but have worked with several frameworks in the past. I am using a Linux development host and have created a docker container as per documentation using:

curl -s https://laravel.build/example-app | bash

After that I have ramped it up using:

cd example-app
./vendor/bin/sail up

I have used migrations to create a post table, which worked fine, and used tinker to add some sample entries. Also, that worked without any issues. But when I am trying to read all table entries in a Controller using the model, I get a MySQL connection refused error.

IlluminateDatabaseQueryException
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `posts`)

After quite a bit of research, I have not been able to solve it. I have tried various solution proposed in different other threads, like:

php artisan config:cache
php artisan config:clear
php artisan cache:clear

no success. I also changed IP address 127.0.0.1 to localhost in .env or towards the docker service mysql as described. All of that with NO success so far.

Summary of what is working:

  • php artisan migrate works fine
  • php artisan tinker works fine
  • phpMyAdmin or other db tools can connect without issues to the DB
  • ramping up a development server with php artisan serve does work and my controller returns table entries as JSON (as expected)

What does NOT work:

  • PostControler and Post::all() results in connection refused when running in docker environment

Has anyone had the same issue as this. It seems everything is setup correctly as everything works on the console and also when firing up a development server. However when running the normal app at http://locahost/posts (for the post controller index) it returns a connection refused.

Environment information

Laravel version: 8.40.0
Laravel locale:en
Laravel config cached: false
PHP version: 8.0.3

config entries

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=user
DB_PASSWORD=password

docker-compose.yml

# For more information: https://laravel.com/docs/sail
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - redis
            - selenium
    mysql:
        image: 'mysql:8.0'
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail
        healthcheck:
          test: ["CMD", "mysqladmin", "ping"]
    redis:
        image: 'redis:alpine'
        ports:
            - '${FORWARD_REDIS_PORT:-6379}:6379'
        volumes:
            - 'sailredis:/data'
        networks:
            - sail
        healthcheck:
          test: ["CMD", "redis-cli", "ping"]
    meilisearch:
        image: 'getmeili/meilisearch:latest'
        ports:
            - '${FORWARD_MEILISEARCH_PORT:-7700}:7700'
        volumes:
            - 'sailmeilisearch:/data.ms'
        networks:
            - sail
    mailhog:
        image: 'mailhog/mailhog:latest'
        ports:
            - '${FORWARD_MAILHOG_PORT:-1025}:1025'
            - '${FORWARD_MAILHOG_DASHBOARD_PORT:-8025}:8025'
        networks:
            - sail
    selenium:
       image: 'selenium/standalone-chrome'
       volumes:
            - '/dev/shm:/dev/shm'
       networks:
           - sail
    phpMyAdmin:
        image: 'phpmyadmin:latest'
        ports:
            - 8080:80
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
        links:
            - 'mysql:db'
        depends_on:
            - mysql
        networks:
            - sail
networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local
    sailredis:
        driver: local
    sailmeilisearch:
        driver: local

Post Controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsPost;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        return Post::all();
        //return view('posts.index');

    }
...

4

Answers


  1. Chosen as BEST ANSWER

    I have found a solution to the issue.

    Changing to localhost did end trying to use a socket, which apparently did not work. I even added the docker mysql socket to the php.ini as default_socket, but it did not resolve anything.

    Solution:

    I have changed localhost/127.0.0.1 to the real IP address of my machine and now everything works as expected.


  2. I had the same problem and fixed just by converting DB_HOST constant in the .env File FROM 127.0.0.1 into localhost
    JUST DO THIS AS GIVEN IN THE BELOW LINE
    DB_HOST = localhost.

    No need to change anything into config/database.php

    Don’t forget to run

    php artisan config:clear
    
    Login or Signup to reply.
  3. Use localhost instead of 127.0.0.1 (in your .env file) and configure your .env database part:

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

    In your config folder database.php configure the MySQL part:

    'mysql' => [
        'driver' => 'mysql',
        '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' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],
    

    After that run these commands:

    //---Remove the configuration cache file
    php artisan config:cache;
    php artisan config:clear;
    

    If your answer is not solved go to the link below:

    Source: PDOException SQLSTATE[HY000] [2002] No such file or directory

    Login or Signup to reply.
  4. As the OP mentioned he uses IP address of container, it’s not a good practice to do that since the IP address may change.

    Change your .env file to:

    DB_HOST=mysql
    

    And it will connect this exact container.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search