Facundo Palavecino
Facundo Palavecino

Reputation: 321

Django loses connection to MySQL db after initialization (Docker)

I'm starting to work with Docker, I'm running a Django app in a container, and a MySQL db in another one. Both of them are connected through a docker-compose.yml file.

After building the containers, Django migrations run successfully and the application starts properly.

However, if I connect to the Django container and execute a command (i.e. python manage.py createsuperuser) an OperationalError is raised saying that it is not possible to connect to the database. What can be the problem?

The picture below shows that tables are created in the database (at some point Django does have access to the db)

Django can access the db and run migrations

Accessing the 4rs_backend container (Django) with docker exec -it <container id> sh and executing python manage.py createsuperuser raises:

enter image description here

docker-compose.yml:

version: '3'
services:
   db:
    image: mysql:5.7
    ports:
      - "7000:3306"
    environment:
      MYSQL_PORT: 3306
      MYSQL_USER: admin_test
      MYSQL_ROOT_PASSWORD: '*****'
      MYSQL_PASSWORD: '*****'
      MYSQL_DATABASE: forrealstate
    container_name: mysql_db
  api:
    build: backend
    command: bash -c "BUILD_TYPE='DOCKER' python manage.py makemigrations && BUILD_TYPE='DOCKER' python manage.py migrate && BUILD_TYPE='DOCKER' python manage.py runserver 0.0.0.0:8000"
    container_name: 4rs_backend
    volumes:
      - ./backend:/backend
    ports:
      - "8000:8000"
    depends_on:
      - db

DATABSE config in Settings.py:

BUILD_TYPE = os.environ.get('BUILD_TYPE')
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'forrealstate',
        'USER': 'admin_test' if BUILD_TYPE == 'DOCKER' else 'root',
        'PASSWORD': '********',
        'HOST': 'db' if BUILD_TYPE == 'DOCKER' else '127.0.0.1',
        'PORT': '3306',
        'ATOMIC_REQUESTS': True,
    }
}

I hope you can help me!

Kind regards

EDIT: Answer

Fixed by adding BUILT_TYPE: 'DOCKER' as an environment variable in the api service.

Upvotes: 0

Views: 173

Answers (1)

Marat
Marat

Reputation: 15738

the DB connection depends on an environment variable BUILD_TYPE. In the api container it is set before executing the command. When you attach to the container, this variable is not set, so django uses the default 127.0.0.1 host.

Fix: prepend BUILD_TYPE='DOCKER' to all manage.py commands, e.g.:

BUILD_TYPE='DOCKER' python manage.py createsuperuser

Alternatively, set this variable globally in the container (that's what I would do)

Upvotes: 1

Related Questions