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',
}
}