Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

django - Docker-Compose can't connect to MySQL

I'm trying to connect Django project with MySQL using docker.

I have the problem when upping docker-compose. It says the next error:

super(Connection, self).init(*args, **kwargs2) django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")

I'm using port 3307, should i create first new database schema in my local? Or how can I do it because my default port is 3306 but if i try to use it, it says that is busy.

My code here:

Dockerfile


FROM python:3.7
ENV PYTHONUNBUFFERED 1
ENV LANG=C.UTF-8
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN apt-get update
RUN pip install -r requirements.txt
ADD . /code/


Docker-compose


    version: '2'

services:
  app:
    container_name: container_app
    build:
      context: .
      dockerfile: Dockerfile
    restart: always
    command: bash -c "python3 manage.py migrate && python manage.py shell < backend/scripts/setup.py && python3 manage.py runserver 0.0.0.0:8000"
    links:
      - db
    depends_on:
      - db
    ports:
      - "8000:8000"
  db:
    container_name: container_database
    image: mariadb
    restart: always
    environment:
      MYSQL_ROOT_HOST: 'host.docker.internal'
      MYSQL_DATABASE: 'container_develop'
      MYSQL_USER: 'root'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - "3307:3307"

settings.py:


DATABASES = {
    'default' : {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database_develop',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'db',
        'PORT': 3307,
        'CHARSET': 'utf8',
        'COLLATION': 'utf8_bin',
        'OPTIONS': {
            'use_unicode' : True,
            'init_command': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED',
        },
    }
}

The thing is that I do not have the database anywhere so I'm using it locally, do I have to upload the db to a server and then use the port that server provides to me? Is there any way to use it locally from docker? Or installing it to docker? So I can share that docker to a friend and he can use the same DB?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the "db" part, in your docker-compose :

ports:
  - "3307:3306"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...