4

I have a configuration of docker-compose, and on building database step, django management throws an error:

django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)")

I think - the docker refusing connections.

Configuration by socket similar not working (Says error connection by socket)

Docker Compose file

version: '3'
services:
  db:
    image: mariadb:5.5
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_DATABASE: "bh"
      MYSQL_USER: "root"
      MYSQL_PASSWORD: "root"
    ports:
      - "3302:3306"


  behealthy_dev:
    build: .
    container_name: behealthy_dev
    expose:
      - "86"
    command: python manage.py runserver 0.0.0.0:80
    volumes:
      - /behealthy_dev/
    ports:
      - "86:86"
    depends_on:
      - db

Dockerfile

FROM python:3.6
ENV PYTHONUNBUFFERED 1
RUN mkdir /behealthy_dev
WORKDIR /behealthy_dev
ADD requirements.txt /behealthy_dev/
RUN pip install -r requirements.txt
ADD . /behealthy_dev/
RUN python manage.py makemigrations
RUN python manage.py migrate
RUN python manage.py collectstatic --noinput

Database settings (settings)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bh',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': 'root',
        'OPTIONS': {
            'sql_mode': 'traditional',
            'init_command': 'SET innodb_strict_mode=1',
            'charset': 'utf8mb4',
        },

    },
}

Have any solutions? I tried to resolve from other stack answer but it's not working for me.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • @sadok-f's answer is important (your database is not on `127.0.0.1`), but also you intrinsically cannot run database migrations from a Dockerfile; it does not have the Compose network environment, and it won't get rebuilt if you delete and recreate the database. – David Maze Aug 08 '19 at 11:27

1 Answers1

2

in your service behealthy_dev change the MySQL host from

'HOST': '127.0.0.1'

to

'HOST': 'db',

Edit: Change also the MYSQL_ROOT_PASSWORD: "root" to:

`MYSQL_ROOT_PASSWORD: "rootpassword"`

and your Database settings to:

'PASSWORD': 'rootpassword',
sadok-f
  • 1,387
  • 15
  • 28