Reputation: 775
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?
Upvotes: 4
Views: 9013
Reputation: 60114
The @Nico answer my fixed your service accessibility from outside of the container, mean if try to access it from the host it should work.
But the error will arise during service to service communication. You should not use publish port in service to service communication or another word you must use container port in service to service communication.
Change the port in connection from 3307
to 3306
DATABASES = {
'default' : {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database_develop',
'USER': 'root',
'PASSWORD': 'password',
'HOST': 'db',
'PORT': 3306,
'CHARSET': 'utf8',
'COLLATION': 'utf8_bin',
'OPTIONS': {
'use_unicode' : True,
'init_command': 'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED',
},
}
}
Upvotes: 3