0

I am trying to dockerize my existing Django Rest project. I am using MySQL database instead of default SqlLite.

My Dockerfile looks like following:

FROM python:2.7

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

and Docker-compose:

version: '3'

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

  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes: 
      - .:/code
    ports:
      - "8000:8000"

I did not run docker-compose run web python manage.py migrate

docker-compose build is successful

However docker-compose up fails eventually saying Can't connect to local MySQL server. I am guessing that I need to install MySQl in my container as well, but do not know how. What am I missing in my Dockerfile or docker-compose?

UPDATE: My settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', #django.db.backends.mysql 
        'NAME': 'libraries', #local: libraries #server: 
        'USER': 'root', #root #root
        'PASSWORD': 'root', #local: root #server: 
        'HOST': 'localhost', #local: localhost  #server:
        'PORT': '3306',
    }
}
2
  • The mysql is already installed on the corresponding container. I guess the problem lies on how you connect to MySQL in your Python code. Can you post that Python part here as well as the detailed error log? Commented Jan 11, 2018 at 15:55
  • Hi! I updated my question with settings.py and another try for docker-compose with some settings Commented Jan 11, 2018 at 15:59

1 Answer 1

1

Change the HOST in the database settings from localhost to db. There's no MySQL in the web container so the Python code couldn't connect to the db.

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

8 Comments

Okay thanks! One quick question: I already have tables in my local database. Do I need to run docker-compose web run python manage.py migrate before build or up?
It still gave me : "Access denied for user 'root'@'172.18.0.3' (using password: YES)"
@Nitish If you sure that the db is synced without your latest schema, you can skip it. However, there's no harm if you run migrate every time.
@Nitish didn't you set the db user to docker, not root ?
I am bit confused here. Must I change user to docker in settings.py as well?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.