Nikul Panchal
Nikul Panchal

Reputation: 1673

Getting error : Unknown MySQL server host 'db' (-2) in django python for docker

I am new here in docker, and I am working on django python. When I try to run this command:

docker-compose run app sh -c "python app/manage.py migrate" 

I am getting error Unknown MySQL server host 'db' (-2), can anyone please help me to resolve this issue ? Here I have added my whole dockerfile and db connection:

Dockerfile

FROM python:3.7
ENV PYTHONUNBUFFERED 1

RUN apt-get update && apt-get install -y --no-install-recommends \
        python-dev \
        default-libmysqlclient-dev \
        && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY requirements.txt /requirements.txt
RUN pip install -r /requirements.txt

RUN mkdir /app
COPY ./ /app

docker-compose.yml

version: "3"
services:

  app:
    build:
      context: .
    ports:
      - "8000:8000"
    volumes:
      - ./:/app
    command: >
      sh -c "python app/manage.py runserver 0.0.0.0:8000"

# Services
  db:
    image: mysql:5.7
    #restart: no
    environment:
      # Password for root access
       MYSQL_ROOT_PASSWORD: '12345678'
       MYSQL_DATABASE: 'trail_risk_inc_backend'
    ports:
      # <Port exposed> : < MySQL Port running inside container>
      - '3306'
    expose:
      # Opens port 3306 on the container
      - '3306'
      # Where our data will be persisted
    volumes:
      - ./db-init:/docker-entrypoint-initdb.d

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'trail_risk_inc_backend',
        'USER': 'root',
        'PASSWORD': '12345678',
        'HOST': 'db',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

Upvotes: 3

Views: 6240

Answers (1)

LinPy
LinPy

Reputation: 18608

the problem is with your command:

docker-compose run app sh -c "python app/manage.py migrate" 

that will start only the app container but not the db.

try to start your stack with:

docker-compose up -d 

then run your command so:

docker exec -ti MY_APP_CON sh -c "python app/manage.py migrate"

Upvotes: 1

Related Questions