cwang
cwang

Reputation: 1104

docker compose MySQL container [2002] Connection refused

I'm trying to build docker compose containers for Nginx + PHP(Laravel) + MySQL, but I keep getting Connection refused error

docker-compose.yml

version: "3"
services:

    nginx:
        image: nginx:latest
        ports:
            - '8080:80'
        volumes:
            - ./nginx:/etc/nginx/conf.d
            - ./logs/nginx:/var/logs/nginx
            - ./apps:/var/www/html
        depends_on:
            - php
        restart: always

    php:
        image: laradock/php-fpm:2.2-7.2
        volumes:
            - ./apps:/var/www/html
        restart: always
    mysql:
        image: mariadb
        ports:
            - '33060:3306'
        volumes:
            - ./db:/var/lib/mysql
        environment:
            - MYSQL_ROOT_PASSWORD=root
        restart: always

In ./apps I have a brand new Laravel app with basic SQL setup

All containers run without errors, and I can connect to the MySQL container using

mysql -u 127.0.0.1 -P 33060 -u root -p

but I keep getting error 2002 when I try to access from the browser or direct ssh into php container.

I have nginx and mysql running on the server so I use 8080 and 33060 port, not sure if that's the problem.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=root
DB_PASSWORD=secret

Thanks for any help.

Upvotes: 4

Views: 6970

Answers (1)

cwang
cwang

Reputation: 1104

getting idea from this Github Issue

My first guess is that it is dying trying to find the mysql unix socket file, when it needs to be connecting over a non-localhost connection. If you are using the compose file to start them, then you can connect to the dns name provided by docker (ie, links: docker-mysql, sets the dns name to be docker-mysql). So you have to change your connection line:

- php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8', 'root', '123123');"

+ php -r "new PDO('mysql:host=docker-mysql;port=3306;charset=utf8', 'root', '123123');"

solved this by changing the DB_HOST to the docker container name in .env file

DB_HOST=docker_mysql_1

Upvotes: 10

Related Questions