I had created a django application and using mysql as db back-end. Everything was working fine on my local machine so i tried to dockerize this application. And i have written code mentioned below to dockerize my application.
docker-compose.yml
version: '3'
services:
mysql:
image: mysql:latest
command: --default-authentication-plugin=mysql_native_password
ports:
- '3306:3306'
environment:
MYSQL_DATABASE: 'cool_db'
MYSQL_ROOT_PASSWORD: 'hello@123*'
container_name: mysql01
restart: always
web:
build: .
container_name: django01
command: bash -c "python3 manage.py makemigrations && python3 manage.py migrate && python3 manage.py collectstatic --noinput && python3 manage.py runserver 0.0.0.0:8000"
volumes:
- my-vol:/src
ports:
- "8000:8000"
links:
- mysql
depends_on:
- mysql
expose:
- "8000"
restart: always
volumes:
my-vol:
Dockerfile
FROM python:latest
ENV PYTHONUNBUFFERED 1
RUN mkdir /src
WORKDIR /src/
COPY ./requirements.txt /src/requirements.txt
RUN pip install -r /src/requirements.txt
COPY . /src/
EXPOSE 8000
requirements.txt
autopep8==1.5.2
boto3==1.14.7
celery==3.1.24
channels==2.4.0
channels-redis==2.4.2
configparser==5.0.0
django==3.0.3
djangorestframework==3.11.0
mysqlclient==1.4.6
pre-commit==2.2.0
redis==2.10.6
requests==2.23.0
WhiteNoise==5.1.0
settings.py
DATABASES = {
"default": {
"ENGINE": config.get("database", "DATABASE_ENGINE"),
"NAME": config.get("database", "DATABASE_NAME"),
"USER": config.get("database", "DATABASE_USER"),
"PASSWORD": config.get("database", "DATABASE_PASSWORD"),
"HOST": config.get("database", "DATABASE_HOST"),
"PORT": config.get("database", "DATABASE_PORT"),
}
}
config.cfg
[database]
DATABASE_USER: root
DATABASE_PASSWORD: hello@123
DATABASE_HOST: mysql
DATABASE_PORT: 3306
DATABASE_ENGINE: django.db.backends.mysql
DATABASE_NAME: cool_db
But when i run this code using sudo docker-compose up then my django service unable to connect with mysql service and raise this error django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
Although mysql was also running on my system i verified it using sudo docker ps. It listed 2 container was running, Mysql container was running without any problem, But django container due to the error mentioned restarts again and again with the same error.