0

I have a very simple Django project (v.2.2) with Python (v.3.6.9), Docker (v.20.10.3), and docker-compose (v. 1.28.4) running on Ubuntu 18.04.

I'm trying to dockerize Django project with MySQL container. I did all the migrations and have the .sql file of my database. The project works fine without Docker, however, when I run docker-compose up I got the following error:

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

Here's my full configuration: https://github.com/aziele/docker-django-mysql

Briefly, this is my Dockerfile:

FROM python:3.6.9
ENV PYTHONUNBUFFERED 1
COPY ./requirements.txt /requirements.txt
RUN pip install -r /requirements.txt
WORKDIR /app

And these my requirements.txt:

Django==2.2
mysqlclient==2.0.3
django-mysql

The docker-compose.yml file:

version: '3'
services:
  db:
    image: mysql:5.7.33
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: 'projectdb1'
      MYSQL_USER: 'user'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
    volumes:
      - ./db/projectdb1.sql:/docker-entrypoint-initdb.d/projectdb1.sql
    ports:
      - '3307:3306'

  django:
    build:
      context: .
      dockerfile: ./Dockerfile-dev
    volumes:
      - ./src:/app
    command: python manage.py runserver 0.0.0.0:8000
    ports:
     - 8080:8000
    restart: always
    depends_on:
      - db

Also I have change the database configurations in settings.py for this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'projectdb1',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'db',
        'PORT': '3307',   
    }
}
sherlock85
  • 871
  • 2
  • 12
  • 16
  • 1
    You always use the "normal" port number (for MySQL, 3306) when making connections between containers. `ports:` aren't used and aren't required. – David Maze Feb 28 '21 at 11:48
  • @DavidMaze Following your suggestion, I changed the port in `settings.py` from `3307` to `3306`, but still have the same error (please see the full log after running `docker-compose up`: https://github.com/aziele/docker-django-mysql). – sherlock85 Feb 28 '21 at 12:04
  • 1
    The other common problem (and it's very visible in your logs) is that the application container starts up before the database is fully ready, so you get a "connection refused" error even if the connection settings are right. See also [Docker Compose wait for container X before starting Y](https://stackoverflow.com/questions/31746182/docker-compose-wait-for-container-x-before-starting-y) for standard techniques to address this. – David Maze Feb 28 '21 at 12:08

0 Answers0