How to keep Celery running in Django (drf) + Redis + WSGI (EC2) - django

I don't think its a very new question. I just could not find the right answer. I am trying to use Celery for background tasks while implementing a backend with the Django Rest Framework. I have a Redis server.
Celery is working as expected with
celery worker -A my_project --loglevel=info
However, it does not work if I sop this command. How do I keep that running? I have found a blog with supervisor. I just want to know what is the standard (as well as easier) to do this.

What you should do is go for docker and use docker-compose for your services. But if you're just testing stuff:
$ nohup celery worker -A my_project --loglevel=info &
& is used to take the process to the background, you can recall it using fg, suspend it to bg using Ctrl + Z, nohup makes sure that celery will remain functioning even if you close the ssh session.
Edit: The only drawback using this method, is that if the process exits, then you'll have to invoke it again. In a production environment, you should go for docker with docker-compose.

Related

why would you separate a celery worker and django container?

I am building a django app with celery. I tried composing a docker-compose without a container for the worker. In my Dockerfile for django, an entrypoint running the celery worker and django app:
...
python manage.py migrate
celery -A api worker -l INFO --detach
python manage.py runserver 0.0.0.0:8000
The celery will run using this order but not django runserver. I have seen in tutorials that they separated the django container from woker container or vice-versa. I do not see the explanation for this separation. I also observed that the two python container (django, worker) has the same volume. How can celery add tasks if it has a different environment with django? In my mind there would be two django apps (the same volume) for two containers only 1 running the runserver, and the other one running the celery worker. I do not understand the separation.
You should aim to set up your containers to run only a single foreground process in each container, and no background processes. Even in this simple example, there are two obvious advantages: if the Celery worker fails, you can restart a standalone container, but it's invisible to Docker as a background process; and you can separately read the docker logs of the Web server and background worker without having them intertwined. At larger scale you can imagine wanting to run different numbers of Django and Celery containers depending on your load.
To make this work it's important that the entrypoint script not run the program directly. It is passed the (possibly overridden) container command as arguments, and you can use a special shell construct to run that
#!/bin/sh
./manage.py migrate
exec "$#"
In the Dockerfile, declare both the ENTRYPOINT and a default CMD to run, say, the Web server
ENTRYPOINT ["./entrypoint.sh"] # probably unchanged, must be JSON array syntax
CMD ["./manage.py", "runserver", "0.0.0.0:8000"]
In a Compose setup, you can run multiple containers off the same image, but override the command: for a Celery worker.
version: '3.8'
services:
web:
build: .
ports: ['8000:8000']
environment:
REDIS_HOST: redis
worker:
build: .
command: celery -A api worker -l INFO
environment:
REDIS_HOST: redis
redis:
image: redis
The main application communicates with the worker via a queue in Redis (or another store), so there's no need for them to be in the same container.
As Celery documentation mentions:
Celery communicates via messages, usually using a broker to mediate
between clients and workers. To initiate a task the client adds a
message to the queue, the broker then delivers that message to a
worker.
Meaning the communication between the Client (Django) and Worker (Celery) are done through a message queue. Hence it does not matter if the workers and clients in separate containers or even separate machines. If the Client can access the message queue (for example using Redis or RabbitMQ) and worker can pop tasks from that queue, it will always work.
About the docker-compose part, there is no ideal standard for keeping or separating Celery and Django. You can put them in same container or not, it is up to you and what are the requirements of the project. If you are using two containers, then they need to share volumes because of the source code and any other data which are needed for executing tasks.

Using Celery/RabbitMQ/Flower in deployment with Django Website

I have a django website that utilizes celery scheduling async tasks. When I am in development mode, I run the commands:
celery -A proj worker --pool=solo -l INFO
flower -A proj --port:5555
celery -A proj beat -l info
for my project to work. How can I run these commands on a cloud based hosting service such as pythonanywhere. In development I would go to localhost and port number to view rabbitmq and flower. How will this work in deployment?
That would not work on PythonAnywhere. There are other ways to do async in web apps there. https://help.pythonanywhere.com/pages/AsyncInWebApps/

Am I executing celery shared tasks correct?

Here is the way how I start celery periodic tasks. First I execute this command:
celery worker -A my_project.celery
And after that this command:
celery -A my_project beat -l info -S django
After executing these two commands on two different terminal tabs, my celery beat periodic tasks starts running. If I don't run one of the described commands, my periodic tasks do not run. My question is: is there any any way to start the celery with the single command, or even better with runserver command?
Your method of using Celery is correct. You can use parameter -B, --beat to start beat and worker using single command:
# This will start worker AND beat process
celery worker --app=my_project -l=INFO --beat -S django
But do not use this in production, see this note in Celery docs (http://docs.celeryproject.org/en/latest/reference/celery.bin.worker.html):
-B is meant to be used for development purposes. For production environment, you need to start celery beat separately.
Few notes: 1) I think there is no way to run the Celery and runserver together (I honestly think it's not a good idea); 2) I see django-celery tag in your question. This is and old and deprecated way of integrating Django and Celery:
THIS PROJECT IS ONLY REQUIRED IF YOU WANT TO USE DJANGO RESULT BACKEND
AND ADMIN INTEGRATION (Source: https://github.com/celery/django-celery)

running django worker and daphne in docker container

I have django application that run in docker container. Recently i figured out that i'm going to need to add websockets interface to my application. I'm using channels with daphne behind nginx and redis as a cache. The problem is that i have to run django workers and daphne in 1 container.
Script that is running on container startup:
#!/usr/bin/env bash
python wait_for_postgres.py
python manage.py makemigrations
python manage.py migrate
python manage.py collectstatic --no-input
python manage.py runworker --only-channels=http.* --only-channels=websocket.* -v2
daphne team_up.asgi:channel_layer --port 8000 -b 0.0.0.0
But it hangs on running a worker. I tried nohup but it seems to not work. If i run daphne directly from container with docker exec everything works just fine.
This is an old question, but I figured I will answer it anyway, because I recently faced the same issue and thought I can shed some light on this.
How Django channels work
Django Channels is another layer on top of Django and it has two process types:
One that accepts HTTP/Websockets
One that runs Django views, Websocket handlers, background tasks, etc
Basically, when a request comes in, it first hits the interface server (Daphne), which accepts the HTTP/Websocket connection and puts it on the Redis queue. The worker (consumer) then sees it, takes it off the queue and runs the view logic (e.g. Django views, WS handlers, etc).
Why it didn't work for you
Because you only run the worker (consumer) and it's blocking the execution of the interface server (producer). Meaning, that no connections will be accepted and worker is just staring at an empty redis queue.
How I made it work
I run Daphne, redis and workers as separate containers for easy scaling. DB migrations, static file collection, etc are executed only in Daphne container. This container will only have one instance running to ensure that there are no parallel db migrations running.
Workers on the other hand can be scaled up and down to deal with the incoming traffic.
How you could make it work
Split your setup into at least two containers. I wouldn't recommend running everything in one container (using Supervisor for example). Why? Because when the time comes to scale the setup there's no easy way to do it. You could scale your container to two instances, but that just creates another supervisor with daphne, redis, django in it... if you split the worker from daphne, you could easily scale the worker container to deal with growing incoming requests.
One container could run:
#!/usr/bin/env bash
python wait_for_postgres.py
python manage.py migrate
python manage.py collectstatic --no-input
daphne team_up.asgi:channel_layer --port 8000 -b 0.0.0.0
while the other one:
#!/usr/bin/env bash
python wait_for_postgres.py
python manage.py runworker --only-channels=http.* --only-channels=websocket.* -v2
The 'makemigrations' command
There is no need to run the command in the script you provided, if anything it could block the whole thing because of some question it is awaiting input for (e.g. "Did you rename column X to Y?").
Instead, you can execute it in a running container like this:
docker exec -it <container_name> python manage.py makemigrations

Permission problems prevent celery from running as daemon?

I'm currently having some trouble running celery as daemon. I use apache to serve my Django application, so I set uid and gid in celery setting all as "www-data". There are 2 places I know so far that need access permission: /var/log/celery/*.log, /var/run/celery/*.pid, and I already set them owned by "www-data". However, celery couldn't get started when I run sudo service celeryd start. If I get rid of the --uid and --gid option for the command, celery could get started by user "root".
One other thing I noticed is that if I could start celery using "root", it will put some files like: celery.bak, celery.dat, celery.dir in my CELERYD_CHDIR, which is my django application directory. I also changed the application directory owned by "www-data", celery still couldn't get started. I copied all the setting files from another machine in which celery runs fine, so I suppose it's not my setting's problem. Does anyone have any clue? Thanks.
Su to celery user and start celery from the command line. Most likely you have an app log, not celery, that you need permission for.