how can i connect django container to mysql container

  django, docker, mysql

Hi i want to connect django – mysql in each container 🙂

i tried a lot of way but failed..

here is my mysql docker-compose.yaml

version: "3"
services:
  db:
    platform: linux/x86_64
    image: mysql:5.7
    container_name: good-mysql
    ports:
      - "3307:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=test
      - MYSQL_DATABASE=testdb
    command: 
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
    volumes:
      - /Users/Shared/data/mysql-test:/var/lib/mysql
    network_mode: bridge

i used mysql official image

and my django Dockerfile

FROM ubuntu:18.04
FROM python:3.8.6-buster

ENV PYTHONUNBUFFERED 1

# General Packages
RUN apt-get update 
    && apt-get install -y libmariadb-dev 
    && apt-get install -y python3-pip 
    && apt-get install -y build-essential 
    && apt-get install -y libcurl4-openssl-dev 
    && apt-get install -y libssl-dev 
    && pip install --upgrade pip

RUN mkdir -p /project/myproject
COPY ./myproject /project/myproject

RUN mkdir -p /app
    WORKDIR /app

RUN pip install -r requirements.txt

CMD tail -f /dev/null

and docker-compose.yaml

version: '3.8'
services:
    deepnatural-ai-api:
        build: .
        image: deepnatural-ai-api:latest
        container_name: deepnatural-ai-api
        ports:
            - 1000:1000
        external_links:
            - "good-mysql:db"
        network_mode: bridge

and i run docker-compose up -d each container

and access mysql container, run mysql -uroot -p its work!

but when i access django container run migrations its raise error

"Unknown MySQL server host 'db' (-2)")

my django settings.py is

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    '...',
]

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'testdb',
    'USER': 'root',
    'PASSWORD': 'test',
    'HOST': 'db',
    'PORT': '3306',
    'OPTIONS': {'auth_plugin': 'mysql_native_password'},
    }
}

ROOT_URLCONF = 'myproject.urls'

DEFAULT_AUTO_FIELD='django.db.models.AutoField'

STATIC_URL = '/static/'

INTERNAL_IPS = [
    '127.0.0.1',
    '0.0.0.0',
]

i have double check docker network, db host name, password, db name etc…

but django can’t find db host "good-mysql"

please some advice thank you 🙂

Source: Docker Questions

LEAVE A COMMENT