AWS Elastic Beanstalk
Developer Guide (API Version 2010-12-01)
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.Did this page help you?  Yes | No |  Tell us about it...

Deploying a Django Application to AWS Elastic Beanstalk

This section walks you through deploying a sample application to AWS Elastic Beanstalk using eb (an updated command line interface) and Git, and then updating the application to use the Django framework. This example uses a configuration file to customize and configure the Python container. For more information about configuration files, see Customizing and Configuring AWS Elastic Beanstalk Environments. The following frameworks have been tested with AWS Elastic Beanstalk:

  • Django 1.4.1

  • Django 1.3.3

Note

This example uses Amazon RDS, and you may be charged for its usage. For more information about pricing, go to http://aws.amazon.com/pricing/. If you are a new customer, you can make use of the AWS Free Usage Tier. For details, go to http://aws.amazon.com/free/.

Step 1: Set Up Your Git Repository

Eb is a command line interface that enables you to deploy applications quickly and more easily using Git. Eb is available as part of the Elastic Beanstalk command line tools package. Follow the steps below to install eb and initialize your Git repository.

To install eb, its prerequisite software, and initialize your Git repository

Step 2: Set Up Your Python Development Environment

Set up your Python development environment on your local computer and then create the basic structure for your Python application. For more information, go to virtualenv. In this example, we use an Amazon Linux EC2 instance as our local python development environment.

To set up your local Python development environment

  • Install the necessary packages. Python 2.7 or 3.0 is required and only used for eb to run on the Linux and Mac operating systems. It is best practice to develop your application using the same Python environment that your application will be running in production. Currently, AWS Elastic Beanstalk supports Python 2.6 running on the Amazon Linux 2012.03 AMI. In this example, we will set up two different environments: one for application development and one for deployment. On your local computer, make sure you have the folllowing installed.

    $ sudo su - 
    $ yum install -y python27 python27-devel
    $ yum install -y gcc mysql mysql-devel
    $ yum install -y python-devel
    $ yum install -y git
    $ wget https://s3.amazonaws.com/elasticbeanstalk/cli/AWS-ElasticBeanstalk-CLI-2.4.zip
    $ unzip AWS-ElasticBeanstalk-CLI-2.4.zip
    $ easy_install pip
    $ pip install http://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.7.2.tar.gz

    On your local computer, create a virtual environment for django development.

    $ virtualenv –p python2.6 /tmp/djangodev

    On your local computer, activate virtualenv.

    $ . /tmp/djangodev/bin/activate

    On your local computer inside your virtual environment, install django and mysql-python.

    (djangodev)# pip install django==1.4.1
    (djangodev)# pip install mysql-python==1.2.3

    Create the django project structure.

    (djangodev)# django-admin.py startproject mysite
    (djangodev)# cd mysite

    Freeze the requirements.txt file.

    (djangodev)# pip freeze > requirements.txt

    Note

    Make sure your requirements.txt file contains the following:

    Django==1.4.1
    MySQL-python==1.2.3

    Note

    You can verify that the development server is working by typing the following command on your local computer:

    (djangodev)# python manage.py runserver

    At this point, you should see the introductory Django page if you start up the dev server. Be sure to stop the dev server before continuing.

    Next, you will configure the AWS Elastic Beanstalk using eb from your local computer.

Step 3: Configure AWS Elastic Beanstalk

You use eb, a command line tool, to configure AWS Elastic Beanstalk. If you haven't already installed eb on your local computer, do that now at the AWS Sample Code & Libraries website. If you are running eb on a Linux operating system, you will need to install Python 2.7 or 3.0.

Before you use eb, you can set your PATH to the location of eb. The following table shows an example for Linux/UNIX and Windows.

On Linux and UNIXOn Windows
$ export PATH=$PATH:<path to unzipped EB CLI package>/eb/linux/python2.7/ C:\> set PATH=%PATH%;<path to unzipped EB CLI package>\eb\windows\

Use the init command, and AWS Elastic Beanstalk will prompt you to enter this information. If a default value is available, and you want to use it, press Enter.

To configure AWS Elastic Beanstalk

  1. Initialize your Git repository. From the /root/mysite directory, type the following:

    git init .
  2. Create an alias to use eb with Python2.7. Specify the path where you installed eb. On a Linux operating system, it would look similar to the following example.

    alias eb="python2.7 ../AWS-ElasticBeanstalk-CLI-2.4/eb/linux/python2.7/eb"
  3. From your directory where you created your local repository, type the following command.

    eb init
  4. When you are prompted for the AWS access key, type your access key. To get your access key information, go to Access Credentials.

    Enter your AWS Access Key ID (current value is "AKIAIOSFODNN7EXAMPLE"): 
  5. When you are prompted for the AWS secret key, type your secret key. To get your secret key information, go to Access Credentials.

    Enter your AWS Secret Access Key (current value is "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"): 
  6. When you are prompted for the AWS Elastic Beanstalk region, type the number of the region. For information about this product's regions, go to Regions and Endpoints in the Amazon Web Services General Reference. For this example, we'll use US East (Virginia).

  7. When you are prompted for the AWS Elastic Beanstalk application name, type the name of the application. AWS Elastic Beanstalk auto-generates an application name based on the current directory name if an application name has not been previously configured. In this example, we use djangoapp.

    Enter an AWS Elastic Beanstalk application name (auto-generated value is "windows"): djangoapp

    Note

    If you have a space in your application name, make sure you do not use quotes.

  8. When you are prompted for the AWS Elastic Beanstalk environment name, type the name of the environment. AWS Elastic Beanstalk automatically creates an environment name based on your application name. If you want to accept the default, press Enter.

    Enter an AWS Elastic Beanstalk environment name (current value is "djangoapp-env"): 

    Note

    If you have a space in your application name, make sure you do not have a space in your environment name.

  9. When you are prompted for the solution stack, type the number of the solution stack you want. For this example, we'll use 32bit Amazon Linux running Python.

  10. When you are prompted to create an Amazon RDS DB Instance, type y or n. For this example, we'll type y.

    Create an RDS DB Instance? [y/n]:
  11. When you are prompted to create the database from scratch or a snapshot, type your selection. For this example, we'll use No snapshot.

  12. When you are prompted to enter your RDS user master password, type your password containing from 8 to 16 printable ASCII characters (excluding /,", and @).

    Enter an RDS DB master password: 
    Retype password to confirm: 
  13. When you are prompted to create a snapshot if you delete the Amazon RDS DB Instance, type y or n. For this example, we'll type n. If you type n, then your RDS DB Instance will be deleted and your data will be lost if you terminate your environment.

    You should see a confirmation that your AWS Credential file was successfully updated.

    By default, eb sets the following default values for Amazon RDS.

    • Database engine — MySQL

    • Default version: — 5.5

    • Database name: — ebdb

    • Allocated storage — 5GB

    • Instance class — db.t1.micro

    • Deletion policy — delete

    • Master username — ebroot

  14. When you are prompted to enter your instance profile name, you can choose to create a default instance profile or use an existing instance profile. Using an instance profile enables IAM users and AWS services to gain access to temporary security credentials to make AWS API calls. Using instance profiles prevents you from having to store long-term security credentials on the EC2 instance. For more information about instance profiles, see Granting Permissions to Users and Services Using IAM Roles. For this example, we'll use Create a default instance profile.

After configuring AWS Elastic Beanstalk, you are ready to deploy a sample application.

If you want to update your AWS Elastic Beanstalk configuration, you can use the init command again. When prompted, you can update your configuration options. If you want to keep any previous settings, press the Enter key. If you want to update your Amazon RDS DB configuration settings, you can update your optionsettings file in the .elasticbeanstalk directory, and then use the eb update command to update your AWS Elastic Beanstalk environment.

Step 4: Create an Application

Next, you need to create and deploy a sample application. For this step, you use a sample application that is already prepared. AWS Elastic Beanstalk uses the configuration information you specified in the previous step to do the following:

  • Creates an application using the application name you specified.

  • Launches an environment using the environment name you specified that provisions the AWS resources to host the application.

  • Deploys the application into the newly created environment.

Use the start command to create and deploy a sample application.

To create the application

  • From your directory where you created your local repository, type the following command.

    eb start

This process may take several minutes to complete. AWS Elastic Beanstalk will provide status updates during the process. If at any time you want to stop polling for status updates, press Ctrl+C. Once the environment status is Green, AWS Elastic Beanstalk will output a URL for the application.

Step 5: View Application

In the previous step, you created an application and deployed it to AWS Elastic Beanstalk. After the environment is ready and its status is green, AWS Elastic Beanstalk provides a URL to view the application. In this step, you can check the status of the environment to make sure it is set to Green and then copy and paste the URL to view the application.

Use the status command to check the environment status, and then use the URL to view the application. Use --verbose to get detailed status information.

To view an application

  1. From your directory where you created your local repository, type the following command.

    eb status --verbose

    AWS Elastic Beanstalk displays the environment status. If the environment is set to green, then AWS Elastic Beanstalk displays the URL for the application. If you attached an RDS DB Instance to your environment, your RDS DB information is displayed.

  2. Copy and paste the URL into your web browser to view your application. You should see the following welcome page.

Step 6: Update Application

After you have deployed a sample application, you can update it with your own application. In this step, we'll update the sample application to use the Django framework.

To update the sample application

  1. On your local computer, create an .ebextensions directory in the top-level directory of your source bundle. In this example, we use /root/mysite/.ebextensions.

    mkdir .ebextensions
  2. Create a configuration file with the extension .config (e.g., myapp.config) and place it in the .ebextensions top-level directory of your source bundle. For more information about the configuration file, see Customizing and Configuring a Python Container.

    container_commands:
      01_syncdb:    
        command: "django-admin.py syncdb --noinput"
        leader_only: true
    
    option_settings:
      - namespace: aws:elasticbeanstalk:container:python
        option_name: WSGIPath
        value: mysite/wsgi.py
      - option_name: DJANGO_SETTINGS_MODULE
        value: mysite.settings
      - option_name: AWS_SECRET_KEY
        value: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
      - option_name: AWS_ACCESS_KEY_ID
        value: AKIAIOSFODNN7EXAMPLE

    In this example, the syncdb command is run on the command header during deployment. The environment variable, DJANGO_SETTINGS_MODULE is set to mysite.settings, and is available to the commands specified in the commands section. WSGIPath for mod_wsgi points to mysite/wsgi.py, which is one of the autogenerated files from the django-admin.py startproject command. For more information about these options, see Python Container Options.

    Note

    The DJANGO_SETTINGS_MODULE, AWS_SECRET_KEY, and AWS_ACCESS_KEY_ID settings are passed in as environment variables and will be available to your application. It is not necessary to provide a "namespace" key to pass in environment variables.

  3. On your local computer, edit /root/mysite/settings.py to use Amazon RDS. AWS Elastic Beanstalk has built-in support for Amazon RDS, so when you launch a Python container, you can associate an Amazon RDS DB Instance. The values of the Amazon RDS parameters are available through environment variables.

    import os 
     
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }
  4. Add your files to your local Git repository, and then commit your change.

    git add .
    git commit -m "eb configuration"

    Note

    For information about Git commands, go to Git - Fast Version Control System.

  5. Create an application version matching your local repository and deploy to the Elastic Beanstalk environment if specified.

    git aws.push

    You can also configure Git to push from a specific branch to a specific environment. For more information, see Deploying a Git Branch to a Specific Environment.

  6. Use the eb status --verbose command to check your environment status. When your environment is green and ready, refresh your web browser to view your updated application. You should see the following.

You can access the logs for your EC2 instances running your application. For instructions on accessing your logs, see Working with Logs.

Step 7: Configure the Django Admin Site (Optional)

Now that you have your Django application up and running, you can optionally configure the admin interface. For more information, go to The Django admin site.

To configure the Django admin site

  1. On your local computer, edit the /root/mysite/mysite/settings.py file with the following:

    • Uncomment the following line in INSTALLED_APPS:

      'django.contrib.admin'

      Your snippet should look similar to the following:

      INSTALLED_APPS = (
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.sites',
          'django.contrib.messages',
          'django.contrib.staticfiles',
          # Uncomment the next line to enable the admin:
          'django.contrib.admin',
          # Uncomment the next line to enable admin documentation:
          # 'django.contrib.admindocs',
      )
    • Change the value of STATIC_ROOT to create a static directory in the top level of your source bundle that will contain static content:

      STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'static')
  2. On your local computer, edit the /root/mysite/mysite/urls.py to uncomment out four lines. The file should look like the following:

    from django.conf.urls import patterns, include, url
    
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('',
        # Examples:
        url(r'^$', 'mysite.views.home', name='home'),
        # url(r'^mysite/', include('mysite.foo.urls')),
    
        # Uncomment the admin/doc line below to enable admin documentation:
        # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    
        # Uncomment the next line to enable the admin:
        url(r'^admin/', include(admin.site.urls)),
    )
  3. On your local computer, create a file called views.py in the /root/mysite/mysite directory.

    from django.http import HttpResponse
    
    def home(request):
        return HttpResponse("Hello from django, try out <a href='/admin/'>/admin/</a>\n")
  4. On your local computer, create a file called createadmin.py and place it in a directory called scripts in your top level directory (/root/mysite/). Make the script executable.

    mkdir scripts
    #!/usr/bin/env python
    
    from django.contrib.auth.models import User
    if User.objects.count() == 0:
        admin = User.objects.create(username='admin')
        admin.set_password('admin')
        admin.is_superuser = True
        admin.is_staff = True
        admin.save()
    chmod +x scripts/createadmin.py

    This creates a user with username/password of admin/admin if there are no users in the database yet.

  5. On your local computer, update your configuration file (e.g., myapp.config) in the .ebextensions directory.

    container_commands:
      01_syncdb:
        command: "django-admin.py syncdb --noinput"
        leader_only: true
      02_createadmin:
        command: "scripts/createadmin.py"
        leader_only: true
      03_collectstatic:
        command: "django-admin.py collectstatic --noinput"
        
    option_settings:
      - namespace: aws:elasticbeanstalk:container:python
        option_name: WSGIPath
        value: mysite/wsgi.py
      - namespace: aws:elasticbeanstalk:container:python:staticfiles
        option_name: /static/
        value: static/
      - option_name: DJANGO_SETTINGS_MODULE
        value: mysite.settings
      - option_name: AWS_SECRET_KEY
        value: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
      - option_name: AWS_ACCESS_KEY_ID
        value: AKIAIOSFODNN7EXAMPLE
    

    The three commands will create the initial database tables, create a user with username "admin" password "admin", and collect all the static files used by the admin interface and bundle them in the "static/" directory of your app directory. Files in your directory on your EC2 instance will be mapped to <your domain>/static/*. For more information about the option settings, see Python Container Options.

    Note

    The DJANGO_SETTINGS_MODULE, AWS_SECRET_KEY, and AWS_ACCESS_KEY_ID settings are passed in as environment variables and will be available to your application. It is not necessary to provide a "namespace" key to pass in environment variables.

  6. Add your files to your local Git repository, commit your change, and redeploy.

    git add .
    git commit -m "configure admin interface"
    git aws.push

Step 8: Clean Up

If you no longer want to run your application, you can clean up by terminating your environment and deleting your application.

Use the stop command to terminate your environment and the delete command to delete your application.

To delete the application

  1. From your directory where you created your local repository, type the following command.

    eb stop

    This process may take a few minutes. AWS Elastic Beanstalk will display a message once the environment has been successfully terminated.

    Note

    If you attached an RDS DB Instance to your environment, your RDS DB will be deleted, and you will lose your data. To save your data, create a snapshot before you delete the application. For instructions on how to create a snapshot, go to Creating a DB Snapshot in the Amazon Relational Database Service User Guide.

  2. From your directory where you installed the command line interface, type the following command.

    eb delete

    AWS Elastic Beanstalk will display a message once it has successfully deleted the application.