Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 942
LeshaZ Avatar asked Dec 10 '22 03:12

LeshaZ


1 Answers

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/

like image 105
michalhosna Avatar answered Dec 27 '22 11:12

michalhosna