Auto-reload Development Mode — For celery worker using docker-compose and Django management commands.
If you are using docker-compose for Django projects with celery workers, I can feel your frustration and here is a possible solution to that problem.
Celery provided auto-reload support until version 3.1, but discontinued because they were facing some issues and having a hard time implementing this feature as you can read on this GitHub issue. So now we are undoubtedly on our own.
Docker provides functionality called volumes and so it has provided us a way to use ‘python manage.py runserver’ command so we don’t have to restart the server every time. Following is the common way to do it-
As you can see, I have used `volumes` to sync my current directory with the code directory of the container. It will use the same code and in entrypoint file is as follows.
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py collectstatic --noinput
python3 manage.py runserver 0.0.0.0:8000
So now the code is in continuous sync and now we can use runserver command to make our development process faster and we can also use this same trick to auto-reload celery worker. You can see `runserver` command file on GitHub.
Django also provides a functionality to create management command for our apps. To create command, You will need to create a management package with commands package inside it.
Now, You will need to create celery.py file in commands package as you can see in the image. copy&paste the following code.
from django.core.management.base import BaseCommand
from django.utils import autoreload
def restart_celery(*args, **kwargs):
kill_worker_cmd = 'pkill -9 celery'
start_worker_cmd = 'celery -A my_celery_project worker -l info'
def handle(self, *args, **options):
self.stdout.write('Starting celery worker with autoreload...')
autoreload.main(restart_celery, args=None, kwargs=None)
As you can see we make use of the same auto-reload functionality which Django developed to restart its local development server. You can use this command in the docker-compose file as following.
command: python3 manage.py celery
It will auto-restart itself whenever you make the code changes.