Deploying a Django Application to Elastic Beanstalk
This tutorial walks through the deployment of a default Django website to an Elastic Beanstalk environment running Python 2.7. The tutorial uses the EB CLI as a deployment mechanism, but you can also use the AWS Management Console to deploy a ZIP file containing your project's contents. The EB CLI is an interactive command line interface written in Python that uses the Python SDK for AWS (boto).
To use any Amazon Web Service (AWS), including Elastic Beanstalk, you need to have an AWS account and credentials. To learn more and to sign up, visit https://aws.amazon.com/.
To follow this tutorial, you should have all of the Common Prerequisites for Python installed, including the following packages:
The Django framework will be installed as part of the tutorial.
Creating environments with the EB CLI requires a service role. You can create a service role by creating an environment in the Elastic Beanstalk
Management Console. If you don't have a service role, the EB CLI will attempt to create one when
Set Up a Python Virtual Environment with Django
Create a virtual environment with virtualenv and use it to install Django and its dependencies. By using a virtual environment, you can discern exactly which packages are needed by your application so that the required packages are installed on the EC2 instances that are running your application.
To set up your virtual environment
Create a virtual environment named
Activate the virtual environment:
source ~/eb-virt/bin/activate(eb-virt) ~$
You will see
(eb-virt)prepended to your command prompt, indicating that you're in a virtual environment.
Use pip to install Django by typing:
pip install django==1.9.2
To verify that Django has been installed, type:
pip freezeDjango==1.9.2 wheel==0.29.0
This command lists all of the packages installed in your virtual environment. Later you will use the output of this command to configure your project for use with Elastic Beanstalk.
Create a Django Project
Now you are ready to create a Django project and run it on your machine, using the virtual environment.
To generate a Django application
Activate your virtual environment:
django-admin startprojectcommand to create a new Django project named
django-admin startproject ebdjango
This command creates a standard Django site named
ebdjangowith the following directory structure:
~/ebdjango |-- ebdjango | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- manage.py
Run your Django site locally with
python manage.py runserver
http://127.0.0.1:8000/in a web browser to view the site:
Check the server log to see the output from your request. You can stop the web server and return to your virtual environment by typing Ctrl+C:
Django version 1.9.2, using settings 'ebdjango.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Not Found: / [15/Feb/2016 20:14:09] "GET / HTTP/1.1" 200 1767
Configure Your Django Application for Elastic Beanstalk
Now that you have a Django-powered site on your local machine, you can configure it for deployment with Elastic Beanstalk.
By default, Elastic Beanstalk looks for a file called
application.py to start your
application. Since this doesn't exist in the Django project that you've created, some
adjustment of your application's environment is necessary. You will also need to set
environment variables so that your application's modules can be loaded.
To configure your site for Elastic Beanstalk
Activate your virtual environment:
pip freezeand save the output to a file named
pip freeze > requirements.txt
Elastic Beanstalk uses
requirements.txtto determine which package to install on the EC2 instances that run your application.
Create a new directory, called
.ebextensionsdirectory, add a configuration file named
django.configwith the following text:
option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py
WSGIPath, specifies the location of the WSGI script that Elastic Beanstalk uses to start your application.
Deactivate your virtual environment by with the
Reactivate your virtual environment whenever you need to add additional packages to your application or run your application locally.
Deploy Your Site With the EB CLI
You've added everything you need to deploy your application on Elastic Beanstalk. Your project directory should now look like this:
~/ebdjango/ |-- .ebextensions | `-- django.config |-- ebdjango | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- db.sqlite3 |-- manage.py `-- requirements.txt
Next, you'll create your application environment and deploy your configured application with Elastic Beanstalk.
To create an environment and deploy your Django application
Initialize your EB CLI repository with the
eb init -p python2.7 django-tutorialApplication django-tutorial has been created.
This command creates a new application named
django-tutorialand configures your local repository to create environments with the latest Python 2.7 platform configuration.
eb initagain to configure a default keypair so that you can connect to the EC2 instance running your application with SSH:
eb initDo you want to set up SSH for your instances? (y/n):
ySelect a keypair. 1) my-keypair 2) [ Create new KeyPair ]
Select a key pair if you have one already, or follow the prompts to create a new one. If you don't see the prompt or need to change your settings later, run
eb init -i.
Create an environment and deploy you application to it with
eb create django-env
If you see a "service role required" error message, run
eb createinteractively (without specifying an environment name) and the EB CLI will create the role for you.
This command creates a load balanced Elastic Beanstalk environment named
django-env. Creating an environment takes about 5 minutes. As Elastic Beanstalk creates the resources necessary to run your application, it outputs informational messages that the EB CLI relays to your terminal.
When the environment creation process completes, open your web site with
This will open a browser window using the domain name created for your application. You should see the same Django website that you created and tested locally.
If you don't see your application running, or get an error message, see Troubleshooting deployments for help with how to determine the cause of the error.
If you do see your application running, then congratulations, you've deployed your first Django application with Elastic Beanstalk!
Updating Your Application
Now that you have a running application on Elastic Beanstalk, you can update and redeploy your application or its configuration and Elastic Beanstalk will take care of the work of updating your instances and starting your new application version.
For this example, we'll enable Django's admin console and configure a few other settings.
Modify Your Site Settings
By default, your Django web site uses the UTC time zone to display time. You can change
this by specifying a time zone in
To change your site's time zone
... # Internationalization LANGUAGE_CODE = 'en-us' TIME_ZONE =
'US/Pacific'USE_I18N = True USE_L10N = True USE_TZ = True
For a list of time zones, visit this page.
Deploy the application to your Elastic Beanstalk environment:
Create a Site Administrator
You can create a site administrator for your Django application to access the admin console directly from the web site. Administrator login details are stored securely in the local database image included in the default project that Django generates.
To create a site administrator
Initialize your Django application's local database:
python manage.py migrateOperations to perform: Apply all migrations: admin, contenttypes, auth, sessions Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying sessions.0001_initial... OK
manage.py createsuperuserto create an administrator:
python manage.py createsuperuserUsername:
********Superuser created successfully.
To tell Django where to store static files, define
STATIC_ROOT = 'static'
manage.py collectstaticto populate the
python manage.py collectstaticYou have requested to collect static files at the destination location as specified in your settings: ~/ebdjango/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel:
yesCopying 'admin/static/adm/css/rtl.css' Copying 'admin/static/adm/css/changelists.css' Copying 'admin/static/adm/css/fonts.css' ...
Deploy your application:
View the admin console by opening the local site in your browser, appending
/admin/to the site URL, such as:
Log in with the username and password that you configured in step 2:
You can use a similar procedure of local updating/testing followed by
deploy. Elastic Beanstalk takes care of the work of updating your live servers, so you can
focus on application development instead of server administration!
Add a Database Migration Configuration File
You can add commands to your
.ebextensions script that will be run when
your site is updated. This allows you to automatically generate database migrations.
To add a migrate step when your application is deployed
Create a new configuration file named
db-migrate.configwith the following content:
container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: ebdjango.settings
This configuration file runs the
django-admin.py migratecommand during the deployment process, prior to starting your application. Because it runs prior to the application starting, you must also configure the
DJANGO_SETTINGS_MODULEenvironment variable explicitly (usually
wsgi.pytakes care of this for you during startup). Specifying
leader_only: truein the command ensures that it is run only once when you're deploying to multiple instances.
Deploy your application:
Clean Up and Next Steps
To save instance hours and other AWS resources between development sessions, terminate
your Elastic Beanstalk environment with
eb terminate django-env
This command terminates the environment and all of the AWS resources that run within it.
It does not delete the application, however, so you can always create more environments with
the same configuration by running
eb create again. For more information on EB CLI
commands, see Managing Elastic Beanstalk Environments with the EB CLI.
If you are done with the sample application, you can also remove the project folder and virtual environment:
rm -rf ~/eb-virt~$
rm -rf ~/ebdjango
For more information about Django, including an in-depth tutorial, visit the official documentation.
If you'd like to try out another Python web framework, check out Deploying a Flask Application to AWS Elastic Beanstalk.