Home Backend Development Python Tutorial Deploying A Django App: ECs App Runner with External Celery

Deploying A Django App: ECs App Runner with External Celery

Aug 08, 2024 pm 10:54 PM

Wait a minute...

Deploying A Django App: ECs App Runner with External Celery

We have all encountered this situation where we are busy trying to go to production, but a lot of factors account for the choice of your platform of deployment. Emmmm YES, we will go with AWS. Usually after sticking to a platform, we can now rely on some factors such as: architecture, cost, reliability, scalability, availability and feasibility. Guess what!!! This will not be about reliability, scalability, availability and feasibility since AWS is trusted for all those. In this tutorial we will identify the ups and downs of some architecture for your Django App.

Before we proceed let's understand a few prerequisites to perfectly understand what is going on.

:) All the code involved in this tutorial will be available as opensource. Feel free to put your footprint into it.

Prerequisites

Before moving ahead, you are required to:

  • Have an AWS account
  • Have some Django knowledge
  • Understand what queueing, tasks, brokers are

What is Caching and Why do we Cache

Caching is a technique used to temporarily store frequently accessed data in a fast-access location, reducing the time it takes to retrieve this data. In AWS, caching improves application performance and scalability by minimizing the load on primary databases and APIs, thereby speeding up response times for end-users.

We cache to enhance efficiency, reduce latency, and lower costs. By storing data closer to the application, caching decreases the frequency of database queries, network traffic, and computational load. This results in faster data retrieval, improved user experience, and optimized resource usage, which is crucial for high-traffic applications.

Let's be warming up

Deploying A Django App: ECs App Runner with External Celery

  1. EC2:
    From its full meaning Elastic Compute Engine, EC2 are web servers found in AWS datacenters. In others words, EC2 are virtual which you can get from AWS. With all functionalities available you can get one at a very cheap monthly rate under a "pay-as-you-go plan".

  2. AWS App Runner:
    This is a fully managed service that simplifies running and scaling web applications and APIs, allowing developers to quickly deploy from code repositories or container images without infrastructure management.

  3. Celery and Django Celery:
    Celery is an open-source distributed task queue for real-time processing in Python. Django Celery integrates Celery with the Django framework, enabling asynchronous task execution, periodic tasks, and background job management within Django applications. The use case of this technology varies. It can be communication services (SMS, emails), Scheduled Jobs (Crons), and background data processing tasks, such as data aggregation, machine learning model training, or file processing.

  4. Amazon RDS (Relational Database Service):
    It is a managed database service that simplifies setting up, operating, and scaling relational databases in the cloud. It supports various database engines like MySQL, PostgreSQL, Oracle, and SQL Server, providing automated backups, patching, and high availability, freeing users from database administration tasks.

Comparing the EC2 and App Runner in this context

Architectures

Let's study how the app is structured and how the deployment setup would behave.

  1. Deployment setup with AWS App Runner (ECR)
    Deploying A Django App: ECs App Runner with External Celery
    We push our code to GitHub, triggering a CodePipeline workflow. CodePipeline uses CodeBuild to create Docker images stored in Elastic Container Registry (ECR) for versioning releases. This tutorial skips Virtual Private Cloud (VPC) configuration. We ensure application health by constantly monitoring logs using CloudWatch. And a bonus is the quick configuration of the project to use Postgres provide by the AWS RDS and S3 for static files.

  2. Deployment with AWS EC2 Instance
    Deploying A Django App: ECs App Runner with External Celery
    Using a similar process, omitting versioning and ECR, we push our code to GitHub, triggering CodePipeline, which uses CodeBuild to create Docker images stored in ECR for versioning. EC2 instances pull these images to deploy the application within a VPC, making it accessible to end users. The application interacts with RDS for data storage and S3 for static files, monitored by CloudWatch. Optionally we can add an SSL configuration into this instance with options like certbot.

Price Comparison Table

Here’s a hypothetical price comparison between EC2 and App Runner based on typical usage scenarios:

Service Component Cost Breakdown Example Monthly Cost (Estimate)
EC2 Instance Usage t2.micro (1 vCPU, 1 GB RAM) .50
Storage 30 GB General Purpose SSD .00
Data Transfer 100 GB Data Transfer .00
Total .50
App Runner Requests 1 million requests .00
Compute 1 vCPU, 2 GB RAM, 30 hours/month .00
Data Transfer 100 GB Data Transfer .00
Total .00

Ease of Management

Let's have a quick summary about how managing these two resources go.

Factor EC2 App Runner
Setup Manual setup required Fully managed service
Management Overhead High - requires OS updates, security patches, etc. Low - abstracts infrastructure management
Configuration Extensive control over instance configuration Limited control, focuses on simplicity

Scalability

Factor EC2 App Runner
Scaling Setup Manual setup of Auto Scaling groups Automatic scaling based on traffic
Scaling Management Requires configuration and monitoring Managed by AWS, seamless scaling
Flexibility High - granular control over scaling policies Simplified, less flexible

Deployment Speed

Factor EC2 App Runner
Deployment Time Slower - instance provisioning and configuration Faster - managed deployment
Update Process May require downtime or rolling updates Seamless updates
Automation Requires setup of deployment pipelines Simplified, integrated deployment

Customization and Control

Factor EC2 App Runner
Customization Extensive - full control over environment Limited - managed environment
Control High - choose specific instance types, storage, etc. Lower - focus on ease of use
Flexibility High - suitable for specialized configurations Simplified for standard web applications

Security

Factor EC2 App Runner
Security Control High - detailed control over security configurations Simplified security management
Management Requires manual configuration of security groups, IAM Managed by AWS, less granular control
Compliance Extensive options for compliance configurations Simplified compliance management

Project Setup

Given that the comparison of our project does not rely on the project setup itself. We will have a basic Django application with a celery configuration from AWS.
We will go with a basic project using Django.

Installing Dependencies and Project Creation:

The commands should be run in the order below:

# Project directory creation
mkdir MySchedular && cd MySchedular

# Creating an isolated space for the project dependencies
python -m venv venv && source venv/bin/activate

# Dependencies installation
pip install django celery redis python_dotenv

# Creating project and app
django-admin startproject my_schedular . && python manage.py startapp crons

# Let's add a few files to the project skeleton
touch my_schedular/celery.py crons/urls.py crons/tasks.py

At this point in time we can check our project skeleton with this:

tree -I "venv|__pycache__" .

And we should have this one at the moment

    .
    ├── crons
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── migrations
    │   │   └── __init__.py
    │   ├── models.py
+   │   ├── tasks.py
    │   ├── tests.py
+   │   ├── urls.py
    │   └── views.py
    ├── manage.py
    └── my_schedular
        ├── __init__.py
        ├── asgi.py
+       ├── celery.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py

    3 directories, 16 files

Code and Logic

We can proceed now by adding a couple of lines for the logic of out app and covering another milestone for this project.
1- Setting up the celery

# my_schedular/celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

app = Celery('myproject')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

2- Let's overwrite the celery variables to set our broker

# my_schedular/settings.py

CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL ')
CELERY_RESULT_BACKEND = os.getenv('CELERY_RESULT_BACKEND')

3- Update init.py to ensure the app is loaded when Django starts:

# my_schedular/__init__.py
from __future__ import absolute_import, unicode_literals

from .celery import app as celery_app

__all__ = ('celery_app',)

4- We create our task

# crons/tasks.py
from celery import shared_task
import time

@shared_task
def add(x, y):
    time.sleep(10)
    return x + y

5- Let's add our view now, just a simple one with a simple Json response.

# crons/views.py
from django.http import JsonResponse
from crons.tasks import add

def index(request):
    return JsonResponse({"message": "Hello world, your Django App is Running"})

def add_view(request):
    result = add.delay(4, 6)
    return JsonResponse({'task_id': result.id})

6- We cannot have a view, without an endpoint to make it possible to access it

# crons/urls.py
from django.urls import path

from crons.views import add_view, index

urlpatterns = [
    path('', index, name='index'),
    path('add/', add_view, name='add'),
]

7- Adding our apps urls to the general urls.py of the whole project.

# my_schedular/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('/', include('crons.urls')),
]

Adding Environment Variables:

# .env
SECRET_KEY=
DEBUG=
CELERY_BROKER_URL=
CELERY_RESULT_BACKEND=

After proper follow up of all these steps, we have this output:
Deploying A Django App: ECs App Runner with External Celery

AWS Environment Setup

Since we are shipping to AWS We need to configure a few resource to

Creating a new VPC (Virtual Private Cloud)

Deploying A Django App: ECs App Runner with External Celery
We create an isolated environment and a network for a secure access and communication between our resources.

Creating Security Groups

Deploying A Django App: ECs App Runner with External Celery
We create a security group under the previously made VPC and together add inbound and outbound rules to the TCP port 6379 (the Redis Port).

Creating the RedisOSS from ElasticCache

Deploying A Django App: ECs App Runner with External Celery

Basically, AWS Elastic Cache offers us two varieties when it comes to caching, namely: RedisOSS and memCache. RedisOSS offers advanced data structures and persistence features, while Memcached is simpler, focusing on high-speed caching of key-value pairs. Redis also supports replication and clustering, unlike Memcached. Back to business, back to Redis.

Elastic Container Registry (ECR) Setup

Deploying A Django App: ECs App Runner with External Celery
The Creation of an ECR image will be very simple and straight forward.

ONE: Updates to deploy the App Runner

Follow the steps below to have your app runner running.
Deploying A Django App: ECs App Runner with External Celery
Deploying A Django App: ECs App Runner with External Celery
Deploying A Django App: ECs App Runner with External Celery
Here we need to be very technical. A VPC is a secured network where most of our resources lie, since an App runner is not found into a VPC, we will need to provide a secured means for communication between those resources.

Credentials user credentials

For this tutorial we will need an authorization to connect our workflow to our ECR. Then we add the AmazonEC2ContainerRegistryFullAccess permission policy so it can push the image to our AWS ECR.
Deploying A Django App: ECs App Runner with External Celery

Results

When all is done we have this tree structure.
Deploying A Django App: ECs App Runner with External Celery

Deploying A Django App: ECs App Runner with External Celery

You can have the whole code base for this tutorial on My GitHub.

TWO: Deploying to an EC2

We will go with one the easiest EC2 to setup and the one having a free tier, an ubuntu EC2 instance. And The same code base that was used above is the same we are using here.

Creating an EC2

![EC2 1]https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rk8waijxkthu1ule91fn.png)
Deploying A Django App: ECs App Runner with External Celery
Alternatively, we can setup the security group separately.
Deploying A Django App: ECs App Runner with External Celery
Deploying A Django App: ECs App Runner with External Celery
Deploying A Django App: ECs App Runner with External Celery
Deploying A Django App: ECs App Runner with External Celery

Setting up the EC2

Run this script to install necessary dependencies

#!/bin/bash

# Update the package list and upgrade existing packages
sudo apt-get update
sudo apt-get upgrade -y

# Install Python3, pip, and other essentials
sudo apt-get install -y python3-pip python3-dev libpq-dev nginx curl

# Install Redis
sudo apt-get install -y redis-server

# Start and enable Redis
sudo systemctl start redis.service
sudo systemctl enable redis.service

# Install Supervisor
sudo apt-get install -y supervisor

# Install virtualenv
sudo pip3 install virtualenv

# Setup your Django project directory (adjust the path as needed)
cd ~/aws-django-redis

# Create a virtual environment
virtualenv venv

# Activate the virtual environment
source venv/bin/activate

# Install Gunicorn and other requirements
pip install gunicorn
pip install -r requirements.txt

# Create directories for logs if they don't already exist
sudo mkdir -p /var/log/aws-django-redis
sudo chown -R ubuntu:ubuntu /var/log/aws-django-redis

# Supervisor Configuration for Gunicorn
echo "[program:aws-django-redis]
command=$(pwd)/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:8000 my_schedular.wsgi:application
directory=$(pwd)
autostart=true
autorestart=true
stderr_logfile=/var/log/aws-django-redis/gunicorn.err.log
stdout_logfile=/var/log/aws-django-redis/gunicorn.out.log
user=ubuntu
" | sudo tee /etc/supervisor/conf.d/aws-django-redis.conf

# Supervisor Configuration for Celery
echo "[program:celery]
command=$(pwd)/venv/bin/celery -A my_schedular worker --loglevel=info
directory=$(pwd)
autostart=true
autorestart=true
stderr_logfile=/var/log/aws-django-redis/celery.err.log
stdout_logfile=/var/log/aws-django-redis/celery.out.log
user=ubuntu
" | sudo tee /etc/supervisor/conf.d/celery.conf

# Reread and update Supervisor
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl restart all

# Set up Nginx to proxy to Gunicorn
echo "server {
    listen 80;
    server_name <your_vm_ip>;

    location / {
        proxy_pass http://127.0.01:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    error_log  /var/log/nginx/aws-django-redis_error.log;
    access_log /var/log/nginx/aws-django-redis_access.log;
}" | sudo tee /etc/nginx/sites-available/aws-django-redis

# Enable the Nginx site configuration
sudo ln -s /etc/nginx/sites-available/aws-django-redis /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default

# Test Nginx configuration and restart Nginx
sudo nginx -t
sudo systemctl restart nginx

Results

This setup is available on GitHub on the dev branch, have a look and open a PR.
Deploying A Django App: ECs App Runner with External Celery
Deploying A Django App: ECs App Runner with External Celery

Pricing and Setup Comparison Table

Feature / Service Self-Managed on EC2 (Free Tier) Fully Managed AWS Services
EC2 Instance t2.micro - Free for 750 hrs/mo Not applicable
Application Hosting Self-managed Django & Gunicorn AWS App Runner (automatic scaling)
Database Self-managed PostgreSQL Amazon RDS (managed relational DB)
In-Memory Cache Redis on the same EC2 Amazon ElastiCache (Redis)
Task Queue Celery with Redis AWS managed queues (e.g., SQS)
Load Balancer Nginx (self-setup) AWS Load Balancer (integrated)
Static Files Storage Serve via Nginx Amazon S3 (highly scalable storage)
Log Management Manual setup (Supervisor, Nginx, Redis) AWS CloudWatch (logs and monitoring)
Security Manual configurations AWS Security Groups, IAM roles
Scaling Manual scaling Automatic scaling
Maintenance Manual updates and patches Managed by AWS
Pricing Minimal (mostly within free tier) Higher due to managed services

Cost Summary

  • Setup Using AWS Free Tier: Primarily free if staying within the free tier limits. Potential costs may arise if usage exceeds free tier allowances.
  • Setup Using All Paid AWS Services: Estimated around $41.34 per month, assuming continuous operation of one t2.micro instance for EC2, Elasticache, and RDS, with additional costs for data transfer and storage.

Note: Prices are approximate and can vary based on region and specific AWS pricing changes. Always check the current AWS Pricing page to get the most accurate cost estimates for your specific requirements.

Analysis

  • Self-Managed on EC2: This approach is cost-effective, especially with the use of the AWS free tier. It requires more setup and manual maintenance but provides full control over the environment. Ideal for smaller scale or lower budget projects.
  • Fully Managed AWS Services: While this increases operational costs, it reduces the workload related to infrastructure management, scaling, and maintenance. It’s suitable for larger applications or when operational simplicity and scaling are priorities.

Summary

Nahhhhhhhhhh!!! Unfortunately, there is no summary for this one. Yes, go back up for a better understanding.

Conclusion

The learning path is long and might seems difficult, but one resource at a time, continuously appending knowledge leads us to meet our objectives and goal.

The above is the detailed content of Deploying A Django App: ECs App Runner with External Celery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Polymorphism in python classes Polymorphism in python classes Jul 05, 2025 am 02:58 AM

Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance

Explain Python generators and iterators. Explain Python generators and iterators. Jul 05, 2025 am 02:55 AM

Iterators are objects that implement __iter__() and __next__() methods. The generator is a simplified version of iterators, which automatically implement these methods through the yield keyword. 1. The iterator returns an element every time he calls next() and throws a StopIteration exception when there are no more elements. 2. The generator uses function definition to generate data on demand, saving memory and supporting infinite sequences. 3. Use iterators when processing existing sets, use a generator when dynamically generating big data or lazy evaluation, such as loading line by line when reading large files. Note: Iterable objects such as lists are not iterators. They need to be recreated after the iterator reaches its end, and the generator can only traverse it once.

How to handle API authentication in Python How to handle API authentication in Python Jul 13, 2025 am 02:22 AM

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

How to iterate over two lists at once Python How to iterate over two lists at once Python Jul 09, 2025 am 01:13 AM

A common method to traverse two lists simultaneously in Python is to use the zip() function, which will pair multiple lists in order and be the shortest; if the list length is inconsistent, you can use itertools.zip_longest() to be the longest and fill in the missing values; combined with enumerate(), you can get the index at the same time. 1.zip() is concise and practical, suitable for paired data iteration; 2.zip_longest() can fill in the default value when dealing with inconsistent lengths; 3.enumerate(zip()) can obtain indexes during traversal, meeting the needs of a variety of complex scenarios.

What are python iterators? What are python iterators? Jul 08, 2025 am 02:56 AM

InPython,iteratorsareobjectsthatallowloopingthroughcollectionsbyimplementing__iter__()and__next__().1)Iteratorsworkviatheiteratorprotocol,using__iter__()toreturntheiteratorand__next__()toretrievethenextitemuntilStopIterationisraised.2)Aniterable(like

Explain Python assertions. Explain Python assertions. Jul 07, 2025 am 12:14 AM

Assert is an assertion tool used in Python for debugging, and throws an AssertionError when the condition is not met. Its syntax is assert condition plus optional error information, which is suitable for internal logic verification such as parameter checking, status confirmation, etc., but cannot be used for security or user input checking, and should be used in conjunction with clear prompt information. It is only available for auxiliary debugging in the development stage rather than substituting exception handling.

What are Python type hints? What are Python type hints? Jul 07, 2025 am 02:55 AM

TypehintsinPythonsolvetheproblemofambiguityandpotentialbugsindynamicallytypedcodebyallowingdeveloperstospecifyexpectedtypes.Theyenhancereadability,enableearlybugdetection,andimprovetoolingsupport.Typehintsareaddedusingacolon(:)forvariablesandparamete

Python FastAPI tutorial Python FastAPI tutorial Jul 12, 2025 am 02:42 AM

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ​​for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

See all articles