Daphne Django deployment error 'Exited with status 1/FAILURE' on linux

I have been struggling with this error for hours, when I try to start my daphne.service, shows up this error after executing the command systemctl status daphne.service. I am folliwing this tutorial: https://github.com/mitchtabian/HOWTO-django-channels-daphne . I am using Gunicorn, Nginx and Redis that are working correctly.

Error:

× daphne.service - WebSocket Daphne Service
     Loaded: loaded (/etc/systemd/system/daphne.service; disabled; preset: enabled)
     Active: failed (Result: exit-code) since Sun 2024-04-21 00:37:25 UTC; 31s ago
   Duration: 676ms
    Process: 2998 ExecStart=/home/franreinaudo/venv/bin/python /home/franreinaudo/venv/bin/daphne -b 0.0.0.0 -p 8001 core.asgi:application (code=exited, status=1/F>
   Main PID: 2998 (code=exited, status=1/FAILURE)
        CPU: 673ms

Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Scheduled restart job, restart counter is at 5.
Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: Stopped daphne.service - WebSocket Daphne Service.
Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Start request repeated too quickly.
Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Failed with result 'exit-code'.
Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: Failed to start daphne.service - WebSocket Daphne Service.

daphne.service

[Unit]
Description=WebSocket Daphne Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/home/franreinaudo/test-db
ExecStart=/home/franreinaudo/venv/bin/python /home/franreinaudo/venv/bin/daphne -b 0.0.0.0 -p 8001 core.asgi:application
Restart=on-failure

[Install]
WantedBy=multi-user.target

settings.py

"""
Django settings for core project.

Generated by 'django-admin startproject' using Django 5.0.1.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret key'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['34.176.127.251']

AUTH_USER_MODEL = 'users.User'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}


# Daphne
ASGI_APPLICATION = 'core.asgi.application'

# Celery

CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'America/Argentina/Cordoba'

CELERY_RESULT_BAKCEND = 'django-db'

# Celery Beat

CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler'

# Channels
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('127.0.0.1', 6379)]
        }
    }
}


# Application definition

INSTALLED_APPS = [
    'daphne',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
    'rest_framework_simplejwt',
    'users',
    'farms',
    'django_celery_results',
    'django_celery_beat'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# CORS_ORIGIN_WHITELIST = ('http://localhost:8000', 'http://127.0.0.1:8000',)

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydb',
        'USER': '###',
        'PASSWORD': '###',
        'HOST': 'localhost',
        'PORT': '',
    }
}

asgi.py

"""
ASGI config for core project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""

import os
import farms.routing
import django

from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django_channels_jwt_auth_middleware.auth import JWTAuthMiddlewareStack
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
django.setup()

django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter({
    'http': django_asgi_app,
    'websocket': AllowedHostsOriginValidator(
        JWTAuthMiddlewareStack(
            URLRouter(farms.routing.websocket_urlpatterns)
        )
    )
})

Back to Top