Hi everyone welcome to a new tutorial. Today we’re going to create the basic structure to run Celery + Redis(as a broker) in a Django project with Docker.
You have to install ‘docker’ and ‘docker-compose’ before start this tutorial.
This tutorial will have 2 steps:
- Create the all docker’s files
- Setting up celery
1- Creating all the docker files. This part is based on the official site of docker
First, in a folder(it will contain all your project) we have to create 3 files. The first one, will be the ‘Dockerfile’ for your Django project:
Here we have used python 3 as image to create our Django project and at the same time creating a ‘code’ folder in our container with all the files of our current folder, including the requirements.txt
Now the ‘docker-compose.yml’ file that will have all the logical structure of our containers:
The important parts here is that:
- We are creating the redis server in a container
- The celery process is in another container that will be created with the same image as your Django project
- We’re creating the volume to synchronize our folder with the folder of our Django project
- Linking redis with celery.
Finally, the requirements.txt:
celery==4.1.0
Django==1.11.5
psycopg2==2.7.3.1
redis==2.10.6
This file doesn’t need explanation ejeje :D
At this point you must have something like this:
your folder
│ requirements.txt
│ Dockerfile
| docker-compose.yml
Run:
$ docker-compose docker-compose run web django-admin.py startproject djangorediscelery .
$ docker-compose up
2- Setting up celery
Write this in ‘djangorediscelery/init.py’:
Create a ‘djangorediscelery/celery.py’ file and write this:
Create a ‘djangorediscelery/tasks.py’ file and write this:
In our ‘djangorediscelery/settings.py’ add this:
And that’s it! Now you just need to run again your docker-compose and you should see each 10 seconds in the celery log the task showing “Hello”
I leave you here the code where you can see it!