Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 270
Axel Ros Avatar asked Mar 04 '23 07:03

Axel Ros


1 Answers

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

ports:
  - "3307:3306"
like image 150
Nico Avatar answered Apr 29 '23 04:04

Nico