Docker and Django Rest Framework "unexpectedly dropped the connection"

Viewed 234

Overview

I have a weird situation where when I apply DEFAULT_FILTER_BACKENDS to my Django Rest Framework (DRF) settings, I get a "Safari can't open 0.0.0.0:8000 because the server unexpectedly dropped the connection" error message.

I should note that the config below works perfectly with a standard poetry run python manage.py runserver 0.0.0.0:8000 command, i.e. when I don't use Docker.

My Django settings.py file is standard, except for:

INSTALLED_APPS = [
    ...
    "rest_framework",
    ...
]
REST_FRAMEWORK = {
    "DEFAULT_FILTER_BACKENDS": (
        "django_filters.rest_framework.DjangoFilterBackend",
    ),
}

and when I remove/comment out the "DEFAULT_FILTER_BACKENDS" section, the server works and my pages load perfectly.

Dockerfile

# pull official base image
FROM python:3.9.0-buster

# set work directory
WORKDIR /usr/src/app

# set environment variables
ENV DJANGO_SETTINGS_MODULE=barrys_project.settings
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

# install dependencies
RUN pip install --no-cache-dir --upgrade pip
RUN pip install --no-cache-dir poetry
COPY ./poetry.lock ./pyproject.toml ./
RUN poetry config virtualenvs.create false
RUN poetry install

# copy entrypoint.sh
COPY ./entrypoint.sh ./

# copy project
COPY . .

# run entrypoint.sh
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]

Docker Compose file

version: '3.8'

services:
  web:
    build: ./
    volumes:
      - ./:/usr/src/app/
    command: poetry run python manage.py runserver 0.0.0.0:8000
    ports:
      - 8000:8000
    env_file:
      - ./.env
    depends_on:
      - db

  db:
    image: postgres:13.3-alpine
    volumes:
      - postgres-data:/var/lib/postgresql/data/
    ports:
      - 5432:5432
    environment:
      - POSTGRES_USER=barry
      - POSTGRES_PASSWORD=secret
      - POSTGRES_DB=barrysdatabase

volumes:
  postgres-data:

Entrypoint.sh

#!/bin/sh

poetry run python manage.py migrate

exec "$@"
1 Answers

Turned out there were anomalies in my Docker containers which required:

docker-compose build
Related