Your Location is: Home > Php

Can't connect to mysql DB by doctrine on docker

From: Monaco View: 2510 Mikolao 

Question

Basicly I have a problem with doctrine. It is my first time that I set up a project on docker containers using doctrine and mysql.

So I have docker-compose.yml

version: '3'
services: 
    api: 
        build: 
            context: ./
            dockerfile: Dockerfile
        container_name: php
        depends_on: 
            - database
        volumes: 
            - ./:/var/www/html/
        ports:
            - 8000:80
        networks:
            - backend
    database: 
        container_name: mysql
        image: mysql:8
        command: --default-authentication-plugin=mysql_native_password
        restart: always
        environment: 
            MYSQL_ROOT_PASSWORD: root
            MYSQL_DATABASE: test_db
            MYSQL_USER: user
            MYSQL_PASSWORD: Test1234
        ports: 
            - 3306:3306
        networks:
            - backend
networks:
    backend:
        driver: bridge

and this is my Dockerfile

FROM php:7.4.12-apache

RUN apt-get update && apt-get upgrade -y \
    && docker-php-ext-install mysqli pdo_mysql


RUN apt-get install -y libzip-dev
RUN docker-php-ext-install zip

# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

      
EXPOSE 80

my .env looks like (rest is commented by # at the beginnig)

APP_ENV=dev
APP_SECRET=00b8dcf4c62a3db98abc4ae12dc4a6fd
DATABASE_URL=mysql://user:[email protected]:3306/bf_db

note that there is no difference between localhost or 127.0.0.1 in DATABASE_URL

now when I want to run this command: docker-compose exec api php bin/console doctrine:database:create

I recieve this kind of errors:

[error] Error thrown while running command "doctrine:database:create". 
Message: "An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused"


In AbstractMySQLDriver.php line 112:

  An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused


In Exception.php line 18:

  SQLSTATE[HY000] [2002] Connection refused


In PDOConnection.php line 38:

  SQLSTATE[HY000] [2002] Connection refused

And I really don't know how to handle this

Best answer

there is no difference between localhost or 127.0.0.1 in DATABASE_URL

Because those refer to the PHP contianer, not the other container.

It needs to be database:3306