2

I'm trying to dockerize my Django app which uses mySql but I'm facing some problems. It's the first time I use Docker so there may be something basic which I don't understand.

Following some online tutorials, this is my Dockerfile:

FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD . /code/ RUN pip install --upgrade pip && pip install -r requirements.txt RUN pip install mysqlclient COPY . /code/ 

And this is my docker-compose:

version: '3' services: db: image: mysql:8 ports: - '3306:3306' environment: MYSQL_DATABASE: 'database_name' MYSQL_USER: 'django' MYSQL_PASSWORD: 'django-password' MYSQL_ROOT_PASSWORD: 'password' volumes: - .setup.sql:/docker-entrypoint-initbd.d/setup.sql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db 

settings.py:

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'mysql-db'), 'USER': os.environ.get('MYSQL_USER', 'mysql-user'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'mysql-password'), 'HOST': os.environ.get('MYSQL_DATABASE_HOST', 'db'), 'PORT': os.environ.get('MYSQL_DATABASE_PORT', 3306), } } 

And .env:

MYSQL_DATABASE=database_name MYSQL_USER=django MYSQL_PASSWORD=django-password MYSQL_ROOT_PASSWORD=password MYSQL_DATABASE_HOST=db MYSQL_DATABASE_PORT=3306 

To dockerize the app, I'm using Docker desktop in Windows 10.

After I run:

docker-compose up -d 

I see both containers (db and web) are running, however in the web container I see that django is not able to connect to mySql, as it gives me the error:

django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)") 

I have seem some similar threads around but they didn't help me understand where the problem is, or how to solve it. Please help me to shed some light on the issue, thank you!

1 Answer 1

1

Have you tried starting your db container first?

docker compose up db docker compose build web docker compose up 

Once the services are built, you will be able to docker compose up without starting db container first as containers will be started in the order of depends_on defined in the docker-compose file.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.