Symfony 4 "Connection refused" while trying to connect to docker mysql container
Asked Answered
L

2

6

My question is how to configure connection to mysql container.

Here is my docker-compose.yml

version: '3'
services:
php:
    build: ./php-fpm
    volumes:
        - ./iym:/var/www/iym
        - ./php-fpm/php.ini:/usr/local/etc/php/php.ini
    depends_on:
        - mysql
web:
    build: ./nginx
    ports:
        - "8888:80"
    volumes:
        - ./iym:/var/www/iym
        - ./nginx/iym.conf:/etc/nginx/conf.d/default.conf
    depends_on:
        - php
mysql:
    image: mysql:5.6
    restart: always
    command: --default-authentication-plugin=mysql_native_password
    volumes:
        - ${DB_PATH_HOST}:/var/lib/mysql
    environment:
        MYSQL_ROOT_PASSWORD: "symf0ny"
    ports:
        - "3306:3306"

And here is my DATABASE_URL in .env file

DATABASE_URL=mysql://root:[email protected]:3306/iym

When i try to run php bin/console doctrine:database:create i get an error like "SQLSTATE[HY000] [2002] Connection refused". OS - ubuntu 18.04. What should i do to connect to DB? Many thanks!

Lysozyme answered 4/2, 2019 at 21:6 Comment(3)
Please post the relevant parts of your config files, not images.Colincolinson
Ok. I've just updated my post.Lysozyme
Can you post your whole docker-compose.yml? And where does you PHP run, in another docker-compose service?Orientalism
O
26

I assume you are trying to connect from another container/service defined in docker-compose and you are using current version of docker-compose (2.4 or 3.7)

You need to change

DATABASE_URL=mysql://root:[email protected]:3306/iym

to

DATABASE_URL=mysql://root:symf0ny@mysql:3306/iym

The reason is that 127.0.0.1 is refering to the localhost of the machine on which php runs. In this case it's the php's container localhost. But the db doesn't run there. It runs in another docker container, which can be reached under the service name, mysql in this case.


In docker-compose networking docs is written:

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

but, the service is discoverable under the container name (which is automatically generated to projectName_serviceName_1 (project name begin by default folder name), but also under service name, link and service alias if defined. I would recommend using service name wherever possible.

More in docs: https://docs.docker.com/compose/networking/

Orientalism answered 4/2, 2019 at 21:55 Comment(0)
O
0

In my case, the Docker variable overrides the parameter from .env file and I'm trying to connect to the wrong host. Found that via dd($this->constructPdoDsn($params)) in the Doctrine\DBAL\Driver\PDO\MySQL\Driver::connect, maybe it will be helpful

Odor answered 7/2, 2023 at 12:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.