1

I have dockerized my existing Django Rest project which uses MySQL database.

Dockefile

FROM python:3.6

ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY . /code/
RUN pip install -r requirements.txt

requirements.txt

django
djongo
django-rest-framework
wheel
pillow
mysqlclient
django-cors-headers

docker-compose.yml

version: '3'
volumes:
    portainer:

services:
  db:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: docker
      MYSQL_DATABASE: docker
      MYSQL_USER: docker
      MYSQL_PASSWORD: docker
    ports:
      - "3306:3306"

  web:
    build: .
    command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 "
    volumes: 
      - .:/code
    ports:
      - "8000:8000"
    links:
     - db
  portainer:
   image: portainer/portainer
   ports:
   - "9000:9000"
   volumes:
    - /var/run/docker.sock:/var/run/docker.sock
    - portainer:/data

setting.py

        'ENGINE': 'django.db.backends.mysql', #django.db.backends.mysql 
        'NAME': 'docker', #local: libraries #server: 
        'USER': 'docker', #root #root
        'PASSWORD': 'docker', #local: root #server: 
        'HOST': 'db', #local: localhost  #server:
        'PORT': '3306',

My command 'docker-compose up -d --build' are successful but the restapp container was not started so while checking logs it was showing this error django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'db\' (111 "Connection refused")').

1
  • The very same code worked for me. But I faced another issue, which is django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded which is not relevant for this question Commented Nov 3, 2018 at 7:44

1 Answer 1

1

This may happen if your application container (web here) starts before your database is fully initialized.

You must wait until db service is started (more precisely, until mysql is accepting connections) before starting your application (python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000).

For that, you can use wait-for-it.sh script (check https://docs.docker.com/compose/startup-order/) before running your python commands. Alternatively, you could use a restart policy on your web service (https://docs.docker.com/compose/compose-file/#restart_policy) to automatically restart your service (until database is up).

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.