SlideShare a Scribd company logo
1 of 24
Download to read offline
Scaling Django Apps using
AWS Elastic Beanstalk
Oct 22nd, 2015
Lushen Wu
Founder, Bebop
http://bebop.com
What we will cover
• What is AWS Elastic Beanstalk (EB)?
• What are the advantages of using EB over
managing EC2 instances / Load-balancing / Auto-
scaling myself?
• What are some common issues I might run into
when deploying my Django app to EB?
Introduction: Bebop’s tech stack
Layer Platform / technology
Client-side jQuery
Devtools
Node.js / Gulp / Sass
Django-compressor
Server (application) Django
Server (language) Python 2.7
Amazon AWS EC2 Amazon S3
• CSS
• Images
• Audio
• Etc.
Amazon RDS
• PostgreSQL
Scaling option 1: manage it yourself
Amazon RDS (database)
Amazon S3 (static assets)
Amazon EC2
(cloud computing)
Amazon EC2
(cloud computing)
Amazon EC2
(cloud computing)
User User User User User User
Instances: either manually
boot up instances or configure
an Auto-scaling policy
Load-balancing: point your
DNS host to the Load
Balancer’s IP address instead
of an EC2 public IP
Use a deployment tool like
Fabric to deploy new
application code to multiple
EC2 instances (e.g. run git pull
on every instance)
+
Load-balancing
Auto-scaling
Core concepts primer
What is AWS auto-scaling?
• AWS monitors your EC2 instances
based on metrics that you specify
(e.g. CPU usage, RAM usage, # of
HTTP requests per minute)
• AWS adds or terminates EC2
instances based on your policy
thresholds (e.g. add instance if
average CPU >60% for 5 minutes,
remove if average CPU < 20% for 5
minutes)
What is AWS load-balancing?
• Distributes incoming requests
among multiple EC2 instances
• Usually routes traffic to instance
with lowest CPU load but you can
specify other policies (e.g. latency)
Scaling option 2: AWS Elastic Beanstalk
Amazon RDS (database)
Amazon S3 (static assets)
Amazon EC2
(cloud computing)
Amazon EC2
(cloud computing)
Amazon EC2
(cloud computing)
User User User User User User
EB web console allows
you to easily configure
Load Balancer and
Autoscaling policy
EB command line tool lets
you easily deploy an
application (in this case,
Django code) to all EC2
instances+
Auto-scaling
Load-balancing
Amazon EB
Quick aside: thoughts on “scaling”
Why is scaling necessary?
• AWS EB/EC2 supports horizontal
scaling (adding more instances) as
well as vertical scaling (using more
powerful instances)
• For speed: You want your web app
to load quickly, and avoid downtime
• For availability: if one datacenter
goes down, people can still access
your web app
Other things to keep in mind:
• Scaling can be expensive, and many site speed
bottlenecks are not solved by adding or upgrading
(e.g. render-blocking javascript/css,
uncompressed or unnecessarily large static
assets, too many HTTP requests)
• Make sure you optimize the basics, e.g.:
minified/gzipped assets, backend caching (e.g.
memcached), frontend caching (e.g. varnish) with
selective AJAX fetching
• We are not using EB to scale the database!
Summary of scaling options
AWS Elastic Beanstalk
• Easier to configure than manually setting up Load Balancer / Autoscaling group
• EB handles source code deployment so you don’t have to use tools like Fabric
Docker
• Briefly looked into it and seemed like EB was sufficient for our needs at the moment
• AWS also supports Docker containers
• Docker just acquired Tutum, potentially easier integrated deployment process
Heroku
• Google search for deploying / scaling Django on Heroku returned some worrying forum posts
Others … ?
EB Overview
1. Creating an EB Environment
2. Configuring an EB Environment
• Instances and scaling
• Environment properties
3. Deployment
4. Recap & tricky snags
1. Creating an EB environment
pip install awsebcli
# check we’re good to go
eb --version
# configure eb with your AWS credentials (Access Key ID, Secret Access Key, default
region, etc.)
eb init
# create an EB environment (will add a .elasticbeanstalk and .ebextensions folder in
your project root)
eb create
Getting started with EB
1. Creating an EB environment
Environment type
• Use ‘Web Server’ environment type
for an external-facing web application
• Make sure the Configuration you use
has a matching PostgreSQL version
with your RDS instance (otherwise
you may run into trouble executing
Postgres commands like ‘pgdump’)
1. You can have more than one environment!
• Testing / Staging -> use smallest EC2 size, 1 or 2 instances in group
• Production -> can be larger EC2 size, at least 3 instances in group
• Workers -> integrate with Amazon SQS, do cronjobs, etc.
2. Instances -> scaling -> deployment
EC2 instance management with Elastic Beanstalk
• Pick the type/size of the EC2 instances that EB will automatically launch
• All instances launched by the auto-scaling policy will be of this type/size!
• You can still manage all EC2 instances as you normally would in the AWS web console for EC2
What size should I pick?
• Remember that you are paying for EC2 instances by the hour, and (AFAIK), even a ping or some background
task using CPU will make that instance count as used
• If you spin up a ton of large instances thinking “Just in case I get a ton of traffic” … you’re gonna get a big bill
How many should I get?
• Having 3 means that you can have one instance down/overwhelmed, one instance deploying new application
version, and still have 1 for failover
2. Instances -> scaling -> deployment
Scaling policy
• Specify minimum and maximum # of instances
• Specify triggers to add or terminate EC2 instances (typically based on CPU usage,
RAM usage, or # of HTTP requests)
• Cooldown: minimum amount of time after a scaling event before another scaling
event can happen… prevents “see-sawing” due to traffic micro spikes
Deployment
• Specify batch size (what # or % of instances to deploy to at the same time)
• Maximum # of instances to deploy to simultaneously
• Minimum # of instances in service
• What could be an issue here?
2. EB Environment Properties
A great way to:
• Avoid committing sensitive
credentials (e.g. social API keys,
DB passwords) into source code
• Deploy same source to different
EB environments (e.g. testing /
staging / production may each
target different databases)
3. Deployment Process
pip install awsebcli
# specify which EB environment to target with subsequent commands
eb use {environment-name}
# output status (e.g. whether currently deploying) and health of target EB environment
eb status
# deploy the latest commit in the current git repository
eb deploy
# dumps logs for whole environment (all instances) into a gzipped file in your project folder
eb logs -z
Using EB command line to deploy
3. What actually happens when you deploy?
What happens in your environment during deployment?
1. ‘eb deploy’ creates a zip file of the latest git commit
• The version you are deploying doesn’t need to be pushed to github, it just
needs to be locally committed
• You can use another revision control platform (e.g. mercurial hg) if you want
2. EB uploads zip file to an S3 bucket associated with your Elastic
Beanstalk account, so it’s accessible by the EB environment
3. EB cycles through your instances and deploys the application to
each ‘deployment batch’ (according to your deployment policy)
3. What actually happens when you deploy?
What happens on an instance during deployment?
• EB runs any server commands you specified (e.g. yum install)
• Extracts source of new version into /opt/python/ondeck
• EB runs any container_commands you specified (e.g. manage.py syncdb)
• If an error is encountered, the deployment aborts, no other instances are
attempted, and the current application version remains active
• If no errors are encountered, EB proceed with deployment:
• Links /opt/python/current/ to the /ondeck/ folder above, WSGI updated
• Django project root is always /opt/python/current/app
3. Helping EB find your Django app
• Options specified in .config
files stored in .ebextensions
folder in project root
• Adds application root to
PYTHONPATH
• Points EB to WSGI
application and configure
threading
option_settings:
"aws:elasticbeanstalk:application:environment":
DJANGO_SETTINGS_MODULE: "musicserver.settings"
"PYTHONPATH": "/opt/python/current/app:$PYTHONPATH"
"aws:elasticbeanstalk:container:python":
WSGIPath: musicserver/wsgi.py
NumProcesses: 3
NumThreads: 20
"aws:elasticbeanstalk:container:python:staticfiles":
"/static/": "static/"
Option Settings (Django WSGI config)
3. Customizing server
01_packages.config
Server Commands (this page) and Container Commands (next page)
• Executed in alphabetical order (name them whatever you want)
• You can run arbitrary bash commands, manage linux packages & services, run arbitrary
python code…
More: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html
commands:
set_time_zone:
command: ln -f -s /usr/share/zoneinfo/US/Eastern /etc/localtime
02_timezone.config
packages:
yum:
gcc: []
git: []
postgresql93-devel: []
3. Customizing server
Container Commands
• leader_only means only the first
instance in a deployment will run
the command
• Other useful parameters:
ignoreErrors (true|false), env
(name/value pairs), cwd
• This is also the time to set up
dependencies like running chmod
on executables (targeting the
/ondeck/app folder)
03_django.config
container_commands:
01_migrate:
command: "source /opt/python/run/venv/bin/activate &&
python manage.py migrate --noinput"
leader_only: true
02_collectstatic:
command: "source /opt/python/run/venv/bin/activate &&
python manage.py collectstatic --noinput"
leader_only: true
03_compress:
command: "source /opt/python/run/venv/bin/activate &&
python manage.py compress --force"
4. Recap & tricky snags
• Scaling EC2 instances is only one part of the solution!
• Select the right EC2 image version for EB (with same PostgreSQL version as RDS)
• Watch out for devtools-related deployment errors (e.g. collectstatic or compress)
• Get familiar with the deployment flow
• Zip & upload -> run server commands -> extract to /ondeck folder -> run container
commands -> link from /current folder
• Watch out for deployment batch size and minimum instances settings (avoid
“stalled” deployments)
Sources
# SSH invoke Django shell with virtualenv
sudo su
cd /opt/python/current/app
source /opt/python/current/env
source /opt/python/run/venv/bin/activate
python manage.py shell
Bonus snippet:• Google / various blogs
• AWS walkthrough on EB and Django
• About 3 days of head-banging and a
dozen Monster energy drinks in
August 2015
Question time

More Related Content

What's hot

What's hot (20)

Mitchell Hashimoto, HashiCorp
Mitchell Hashimoto, HashiCorpMitchell Hashimoto, HashiCorp
Mitchell Hashimoto, HashiCorp
 
How Ansible Makes Automation Easy
How Ansible Makes Automation EasyHow Ansible Makes Automation Easy
How Ansible Makes Automation Easy
 
Ansible on aws - Pop-up Loft Tel Aviv
Ansible on aws - Pop-up Loft Tel AvivAnsible on aws - Pop-up Loft Tel Aviv
Ansible on aws - Pop-up Loft Tel Aviv
 
Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012
 
JRubyConf 2009
JRubyConf 2009JRubyConf 2009
JRubyConf 2009
 
Ansible v2 and Beyond (Ansible Hawai'i Meetup)
Ansible v2 and Beyond (Ansible Hawai'i Meetup)Ansible v2 and Beyond (Ansible Hawai'i Meetup)
Ansible v2 and Beyond (Ansible Hawai'i Meetup)
 
Plone Hosting: A Panel Discussion
Plone Hosting: A Panel DiscussionPlone Hosting: A Panel Discussion
Plone Hosting: A Panel Discussion
 
(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014
(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014
(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014
 
Ansible Intro - June 2015 / Ansible Barcelona User Group
Ansible Intro - June 2015 / Ansible Barcelona User GroupAnsible Intro - June 2015 / Ansible Barcelona User Group
Ansible Intro - June 2015 / Ansible Barcelona User Group
 
Corley scalability
Corley scalabilityCorley scalability
Corley scalability
 
Ansible: How to Get More Sleep and Require Less Coffee
Ansible: How to Get More Sleep and Require Less CoffeeAnsible: How to Get More Sleep and Require Less Coffee
Ansible: How to Get More Sleep and Require Less Coffee
 
AVA - a futuristic test runner
AVA - a futuristic test runnerAVA - a futuristic test runner
AVA - a futuristic test runner
 
DevOps for Humans - Ansible for Drupal Deployment Victory!
DevOps for Humans - Ansible for Drupal Deployment Victory!DevOps for Humans - Ansible for Drupal Deployment Victory!
DevOps for Humans - Ansible for Drupal Deployment Victory!
 
Managing AWS infrastructure using CloudFormation
Managing AWS infrastructure using CloudFormationManaging AWS infrastructure using CloudFormation
Managing AWS infrastructure using CloudFormation
 
I can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and SpringI can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and Spring
 
Chasing AMI - Building Amazon machine images with Puppet, Packer and Jenkins
Chasing AMI - Building Amazon machine images with Puppet, Packer and JenkinsChasing AMI - Building Amazon machine images with Puppet, Packer and Jenkins
Chasing AMI - Building Amazon machine images with Puppet, Packer and Jenkins
 
Drupal VM for Drupal 8 Dev - MidCamp 2017
Drupal VM for Drupal 8 Dev - MidCamp 2017Drupal VM for Drupal 8 Dev - MidCamp 2017
Drupal VM for Drupal 8 Dev - MidCamp 2017
 
Ansible Case Studies
Ansible Case StudiesAnsible Case Studies
Ansible Case Studies
 
Dev-Friendly Ops
Dev-Friendly OpsDev-Friendly Ops
Dev-Friendly Ops
 
Configuration primer
Configuration primerConfiguration primer
Configuration primer
 

Viewers also liked

TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
Amazon Web Services
 

Viewers also liked (20)

Django Deployment-in-AWS
Django Deployment-in-AWSDjango Deployment-in-AWS
Django Deployment-in-AWS
 
Reviews.co.uk - Power Of Reviews
Reviews.co.uk - Power Of ReviewsReviews.co.uk - Power Of Reviews
Reviews.co.uk - Power Of Reviews
 
AWS: Scaling With Elastic Beanstalk
AWS: Scaling With Elastic BeanstalkAWS: Scaling With Elastic Beanstalk
AWS: Scaling With Elastic Beanstalk
 
An Engineers Guide to the AWS Ruby SDK
An Engineers Guide to the AWS Ruby SDKAn Engineers Guide to the AWS Ruby SDK
An Engineers Guide to the AWS Ruby SDK
 
AWS EC2 Container Service (ECS) In Action - iMasters Developer Week - Vitoria
AWS EC2 Container Service (ECS) In Action - iMasters Developer Week - VitoriaAWS EC2 Container Service (ECS) In Action - iMasters Developer Week - Vitoria
AWS EC2 Container Service (ECS) In Action - iMasters Developer Week - Vitoria
 
AWS Elastic Beanstalk and Docker
AWS Elastic Beanstalk and DockerAWS Elastic Beanstalk and Docker
AWS Elastic Beanstalk and Docker
 
Docker on AWS - the Right Way
Docker on AWS - the Right WayDocker on AWS - the Right Way
Docker on AWS - the Right Way
 
Docker on AWS
Docker on AWSDocker on AWS
Docker on AWS
 
Apache Spark Clusters for Everyone | AWS Public Sector Summit 2016
Apache Spark Clusters for Everyone | AWS Public Sector Summit 2016Apache Spark Clusters for Everyone | AWS Public Sector Summit 2016
Apache Spark Clusters for Everyone | AWS Public Sector Summit 2016
 
Deployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and ToolsDeployment and Management on AWS:
 A Deep Dive on Options and Tools
Deployment and Management on AWS:
 A Deep Dive on Options and Tools
 
(APP313) NEW LAUNCH: Amazon EC2 Container Service in Action | AWS re:Invent 2014
(APP313) NEW LAUNCH: Amazon EC2 Container Service in Action | AWS re:Invent 2014(APP313) NEW LAUNCH: Amazon EC2 Container Service in Action | AWS re:Invent 2014
(APP313) NEW LAUNCH: Amazon EC2 Container Service in Action | AWS re:Invent 2014
 
Apache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream ProcessingApache Kafka, and the Rise of Stream Processing
Apache Kafka, and the Rise of Stream Processing
 
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
TLS303 How to Deploy Python Applications on AWS Elastic Beanstalk - AWS re:In...
 
Demystifying Stream Processing with Apache Kafka
Demystifying Stream Processing with Apache KafkaDemystifying Stream Processing with Apache Kafka
Demystifying Stream Processing with Apache Kafka
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
 
Data Pipelines with Kafka Connect
Data Pipelines with Kafka ConnectData Pipelines with Kafka Connect
Data Pipelines with Kafka Connect
 
AWS re:Invent 2016: Workshop: Deploy a Swift Web Application on Amazon ECS (C...
AWS re:Invent 2016: Workshop: Deploy a Swift Web Application on Amazon ECS (C...AWS re:Invent 2016: Workshop: Deploy a Swift Web Application on Amazon ECS (C...
AWS re:Invent 2016: Workshop: Deploy a Swift Web Application on Amazon ECS (C...
 
Introduction to Apache Kafka- Part 1
Introduction to Apache Kafka- Part 1Introduction to Apache Kafka- Part 1
Introduction to Apache Kafka- Part 1
 
5 Reasons Why You Should Consider Migrating Web Apps to the Cloud on AWS
5 Reasons Why You Should Consider Migrating Web Apps to the Cloud on AWS5 Reasons Why You Should Consider Migrating Web Apps to the Cloud on AWS
5 Reasons Why You Should Consider Migrating Web Apps to the Cloud on AWS
 
Introducing Apache Kafka's Streams API - Kafka meetup Munich, Jan 25 2017
Introducing Apache Kafka's Streams API - Kafka meetup Munich, Jan 25 2017Introducing Apache Kafka's Streams API - Kafka meetup Munich, Jan 25 2017
Introducing Apache Kafka's Streams API - Kafka meetup Munich, Jan 25 2017
 

Similar to Scaling Django Apps using AWS Elastic Beanstalk

Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...
Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...
Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...
Amazon Web Services
 
UKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basicsUKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basics
Ulrich Krause
 
Migrating enterprise workloads to AWS
Migrating enterprise workloads to AWSMigrating enterprise workloads to AWS
Migrating enterprise workloads to AWS
Tom Laszewski
 

Similar to Scaling Django Apps using AWS Elastic Beanstalk (20)

AWS Elastic Beanstalk: Running Multi-Container Docker Applications - DevDay L...
AWS Elastic Beanstalk: Running Multi-Container Docker Applications - DevDay L...AWS Elastic Beanstalk: Running Multi-Container Docker Applications - DevDay L...
AWS Elastic Beanstalk: Running Multi-Container Docker Applications - DevDay L...
 
DevOps with Elastic Beanstalk - TCCC-2014
DevOps with Elastic Beanstalk - TCCC-2014DevOps with Elastic Beanstalk - TCCC-2014
DevOps with Elastic Beanstalk - TCCC-2014
 
Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...
Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...
Managing Docker & ECS Based Applications with AWS Elastic Beanstalk - DevDay ...
 
Advanced Container Scheduling
Advanced Container SchedulingAdvanced Container Scheduling
Advanced Container Scheduling
 
Distribua, gerencie e escale suas aplicações com o aws elastic beanstalk
Distribua, gerencie e escale suas aplicações com o aws elastic beanstalkDistribua, gerencie e escale suas aplicações com o aws elastic beanstalk
Distribua, gerencie e escale suas aplicações com o aws elastic beanstalk
 
AWS (Hadoop) Meetup 30.04.09
AWS (Hadoop) Meetup 30.04.09AWS (Hadoop) Meetup 30.04.09
AWS (Hadoop) Meetup 30.04.09
 
Deep Dive into AWS Fargate
Deep Dive into AWS FargateDeep Dive into AWS Fargate
Deep Dive into AWS Fargate
 
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
AD113  Speed Up Your Applications w/ Nginx and PageSpeedAD113  Speed Up Your Applications w/ Nginx and PageSpeed
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
 
AWS July Webinar Series-Deploying and Scaling Web Application with AWS Elasti...
AWS July Webinar Series-Deploying and Scaling Web Application with AWS Elasti...AWS July Webinar Series-Deploying and Scaling Web Application with AWS Elasti...
AWS July Webinar Series-Deploying and Scaling Web Application with AWS Elasti...
 
Azure Templates for Consistent Deployment
Azure Templates for Consistent DeploymentAzure Templates for Consistent Deployment
Azure Templates for Consistent Deployment
 
Advanced Container Management and Scheduling
Advanced Container Management and SchedulingAdvanced Container Management and Scheduling
Advanced Container Management and Scheduling
 
Deploy, Scale and Manage your Application with AWS Elastic Beanstalk
Deploy, Scale and Manage your Application with AWS Elastic BeanstalkDeploy, Scale and Manage your Application with AWS Elastic Beanstalk
Deploy, Scale and Manage your Application with AWS Elastic Beanstalk
 
ECS & ECR Deep Dive - 김기완 솔루션즈 아키텍트 :: AWS Container Day
ECS & ECR Deep Dive - 김기완 솔루션즈 아키텍트 :: AWS Container DayECS & ECR Deep Dive - 김기완 솔루션즈 아키텍트 :: AWS Container Day
ECS & ECR Deep Dive - 김기완 솔루션즈 아키텍트 :: AWS Container Day
 
UKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basicsUKLUG 2012 - XPages, Beyond the basics
UKLUG 2012 - XPages, Beyond the basics
 
XPages -Beyond the Basics
XPages -Beyond the BasicsXPages -Beyond the Basics
XPages -Beyond the Basics
 
Aws-What You Need to Know_Simon Elisha
Aws-What You Need to Know_Simon ElishaAws-What You Need to Know_Simon Elisha
Aws-What You Need to Know_Simon Elisha
 
[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the Basics[DanNotes] XPages - Beyound the Basics
[DanNotes] XPages - Beyound the Basics
 
Deploy, Scale and Manage your Application with AWS Elastic Beanstalk
Deploy, Scale and Manage your Application with AWS Elastic BeanstalkDeploy, Scale and Manage your Application with AWS Elastic Beanstalk
Deploy, Scale and Manage your Application with AWS Elastic Beanstalk
 
Migrating enterprise workloads to AWS
Migrating enterprise workloads to AWSMigrating enterprise workloads to AWS
Migrating enterprise workloads to AWS
 
Meanstack overview
Meanstack overviewMeanstack overview
Meanstack overview
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Scaling Django Apps using AWS Elastic Beanstalk

  • 1. Scaling Django Apps using AWS Elastic Beanstalk Oct 22nd, 2015 Lushen Wu Founder, Bebop http://bebop.com
  • 2. What we will cover • What is AWS Elastic Beanstalk (EB)? • What are the advantages of using EB over managing EC2 instances / Load-balancing / Auto- scaling myself? • What are some common issues I might run into when deploying my Django app to EB?
  • 3. Introduction: Bebop’s tech stack Layer Platform / technology Client-side jQuery Devtools Node.js / Gulp / Sass Django-compressor Server (application) Django Server (language) Python 2.7 Amazon AWS EC2 Amazon S3 • CSS • Images • Audio • Etc. Amazon RDS • PostgreSQL
  • 4. Scaling option 1: manage it yourself Amazon RDS (database) Amazon S3 (static assets) Amazon EC2 (cloud computing) Amazon EC2 (cloud computing) Amazon EC2 (cloud computing) User User User User User User Instances: either manually boot up instances or configure an Auto-scaling policy Load-balancing: point your DNS host to the Load Balancer’s IP address instead of an EC2 public IP Use a deployment tool like Fabric to deploy new application code to multiple EC2 instances (e.g. run git pull on every instance) + Load-balancing Auto-scaling
  • 5. Core concepts primer What is AWS auto-scaling? • AWS monitors your EC2 instances based on metrics that you specify (e.g. CPU usage, RAM usage, # of HTTP requests per minute) • AWS adds or terminates EC2 instances based on your policy thresholds (e.g. add instance if average CPU >60% for 5 minutes, remove if average CPU < 20% for 5 minutes) What is AWS load-balancing? • Distributes incoming requests among multiple EC2 instances • Usually routes traffic to instance with lowest CPU load but you can specify other policies (e.g. latency)
  • 6. Scaling option 2: AWS Elastic Beanstalk Amazon RDS (database) Amazon S3 (static assets) Amazon EC2 (cloud computing) Amazon EC2 (cloud computing) Amazon EC2 (cloud computing) User User User User User User EB web console allows you to easily configure Load Balancer and Autoscaling policy EB command line tool lets you easily deploy an application (in this case, Django code) to all EC2 instances+ Auto-scaling Load-balancing Amazon EB
  • 7. Quick aside: thoughts on “scaling” Why is scaling necessary? • AWS EB/EC2 supports horizontal scaling (adding more instances) as well as vertical scaling (using more powerful instances) • For speed: You want your web app to load quickly, and avoid downtime • For availability: if one datacenter goes down, people can still access your web app Other things to keep in mind: • Scaling can be expensive, and many site speed bottlenecks are not solved by adding or upgrading (e.g. render-blocking javascript/css, uncompressed or unnecessarily large static assets, too many HTTP requests) • Make sure you optimize the basics, e.g.: minified/gzipped assets, backend caching (e.g. memcached), frontend caching (e.g. varnish) with selective AJAX fetching • We are not using EB to scale the database!
  • 8. Summary of scaling options AWS Elastic Beanstalk • Easier to configure than manually setting up Load Balancer / Autoscaling group • EB handles source code deployment so you don’t have to use tools like Fabric Docker • Briefly looked into it and seemed like EB was sufficient for our needs at the moment • AWS also supports Docker containers • Docker just acquired Tutum, potentially easier integrated deployment process Heroku • Google search for deploying / scaling Django on Heroku returned some worrying forum posts Others … ?
  • 9. EB Overview 1. Creating an EB Environment 2. Configuring an EB Environment • Instances and scaling • Environment properties 3. Deployment 4. Recap & tricky snags
  • 10. 1. Creating an EB environment pip install awsebcli # check we’re good to go eb --version # configure eb with your AWS credentials (Access Key ID, Secret Access Key, default region, etc.) eb init # create an EB environment (will add a .elasticbeanstalk and .ebextensions folder in your project root) eb create Getting started with EB
  • 11. 1. Creating an EB environment Environment type • Use ‘Web Server’ environment type for an external-facing web application • Make sure the Configuration you use has a matching PostgreSQL version with your RDS instance (otherwise you may run into trouble executing Postgres commands like ‘pgdump’)
  • 12. 1. You can have more than one environment! • Testing / Staging -> use smallest EC2 size, 1 or 2 instances in group • Production -> can be larger EC2 size, at least 3 instances in group • Workers -> integrate with Amazon SQS, do cronjobs, etc.
  • 13. 2. Instances -> scaling -> deployment EC2 instance management with Elastic Beanstalk • Pick the type/size of the EC2 instances that EB will automatically launch • All instances launched by the auto-scaling policy will be of this type/size! • You can still manage all EC2 instances as you normally would in the AWS web console for EC2 What size should I pick? • Remember that you are paying for EC2 instances by the hour, and (AFAIK), even a ping or some background task using CPU will make that instance count as used • If you spin up a ton of large instances thinking “Just in case I get a ton of traffic” … you’re gonna get a big bill How many should I get? • Having 3 means that you can have one instance down/overwhelmed, one instance deploying new application version, and still have 1 for failover
  • 14. 2. Instances -> scaling -> deployment Scaling policy • Specify minimum and maximum # of instances • Specify triggers to add or terminate EC2 instances (typically based on CPU usage, RAM usage, or # of HTTP requests) • Cooldown: minimum amount of time after a scaling event before another scaling event can happen… prevents “see-sawing” due to traffic micro spikes Deployment • Specify batch size (what # or % of instances to deploy to at the same time) • Maximum # of instances to deploy to simultaneously • Minimum # of instances in service • What could be an issue here?
  • 15. 2. EB Environment Properties A great way to: • Avoid committing sensitive credentials (e.g. social API keys, DB passwords) into source code • Deploy same source to different EB environments (e.g. testing / staging / production may each target different databases)
  • 16. 3. Deployment Process pip install awsebcli # specify which EB environment to target with subsequent commands eb use {environment-name} # output status (e.g. whether currently deploying) and health of target EB environment eb status # deploy the latest commit in the current git repository eb deploy # dumps logs for whole environment (all instances) into a gzipped file in your project folder eb logs -z Using EB command line to deploy
  • 17. 3. What actually happens when you deploy? What happens in your environment during deployment? 1. ‘eb deploy’ creates a zip file of the latest git commit • The version you are deploying doesn’t need to be pushed to github, it just needs to be locally committed • You can use another revision control platform (e.g. mercurial hg) if you want 2. EB uploads zip file to an S3 bucket associated with your Elastic Beanstalk account, so it’s accessible by the EB environment 3. EB cycles through your instances and deploys the application to each ‘deployment batch’ (according to your deployment policy)
  • 18. 3. What actually happens when you deploy? What happens on an instance during deployment? • EB runs any server commands you specified (e.g. yum install) • Extracts source of new version into /opt/python/ondeck • EB runs any container_commands you specified (e.g. manage.py syncdb) • If an error is encountered, the deployment aborts, no other instances are attempted, and the current application version remains active • If no errors are encountered, EB proceed with deployment: • Links /opt/python/current/ to the /ondeck/ folder above, WSGI updated • Django project root is always /opt/python/current/app
  • 19. 3. Helping EB find your Django app • Options specified in .config files stored in .ebextensions folder in project root • Adds application root to PYTHONPATH • Points EB to WSGI application and configure threading option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "musicserver.settings" "PYTHONPATH": "/opt/python/current/app:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: musicserver/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" Option Settings (Django WSGI config)
  • 20. 3. Customizing server 01_packages.config Server Commands (this page) and Container Commands (next page) • Executed in alphabetical order (name them whatever you want) • You can run arbitrary bash commands, manage linux packages & services, run arbitrary python code… More: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html commands: set_time_zone: command: ln -f -s /usr/share/zoneinfo/US/Eastern /etc/localtime 02_timezone.config packages: yum: gcc: [] git: [] postgresql93-devel: []
  • 21. 3. Customizing server Container Commands • leader_only means only the first instance in a deployment will run the command • Other useful parameters: ignoreErrors (true|false), env (name/value pairs), cwd • This is also the time to set up dependencies like running chmod on executables (targeting the /ondeck/app folder) 03_django.config container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput" leader_only: true 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" leader_only: true 03_compress: command: "source /opt/python/run/venv/bin/activate && python manage.py compress --force"
  • 22. 4. Recap & tricky snags • Scaling EC2 instances is only one part of the solution! • Select the right EC2 image version for EB (with same PostgreSQL version as RDS) • Watch out for devtools-related deployment errors (e.g. collectstatic or compress) • Get familiar with the deployment flow • Zip & upload -> run server commands -> extract to /ondeck folder -> run container commands -> link from /current folder • Watch out for deployment batch size and minimum instances settings (avoid “stalled” deployments)
  • 23. Sources # SSH invoke Django shell with virtualenv sudo su cd /opt/python/current/app source /opt/python/current/env source /opt/python/run/venv/bin/activate python manage.py shell Bonus snippet:• Google / various blogs • AWS walkthrough on EB and Django • About 3 days of head-banging and a dozen Monster energy drinks in August 2015