Skip to main content

Django and Elastic Beanstalk, a perfect combination

This post gives a minimum working example such that you can launch your Django application on Amazon servers using Elastic Beanstalk. The only things you need is a Django application, Python 3 and an Amazon account. Before we start, make sure you have installed the Amazon CLI. Let’s start!

In this mini-tutorial, I have a Django application named “myapp”. This should be replaced with the name of your Django application.

  1. Start a terminal (often CTRL+T on Linux).
  2. Change the current directory to the directory containing your app. In my case I executed:
    cd ~/myapp
  3. Initialize Elastic Beanstalk inside this directory by executing the following command:
    eb init

    You get a bunch of questions about the server(s) that will be initialized. Answer them regarding your own needs. During the questions, I created a new application named “myapp”. It also recognized that I used Python.

  4. Now we will create some configuration that is executed whenever code is deployed.
    mkdir .ebextensions

    Now, create the following file: “.ebextensions/python.config” and use this boilerplate code:

    container_commands:
      00_setup_database:
        command: "touch db.sqlite3 && chmod 0777 db.sqlite3"
      00_setup_static:
        command: "mkdir static && chmod 0777 static && chmod 0777 ."
      01_collectstatic:
        command: "django-admin.py collectstatic --noinput"
      03_translation:
        command: "django-admin.py compilemessages --locale nl"
      04_migrate:
        command: "django-admin.py migrate --noinput"
        leader_only: true
      05_wsgipass:
        command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
    
    option_settings:
      "aws:elasticbeanstalk:application:environment":
        DJANGO_SETTINGS_MODULE: "myapp.settings"
        PYTHONPATH: "$PYTHONPATH"
      "aws:elasticbeanstalk:container:python":
        WSGIPath: "myapp/wsgi.py"

    This is useful for updating the database automatically or for updating translations or for doing other automated tasks.

  5. You need an environment to deploy your changes to. For this, you should execute the following command:
    eb create my-env

    Here, “my-env” can be replaced with a name of your choice. Common environment names are “production”, “test” and “development”. It takes a while before the environment is created. A perfect time for a coffee break :-). The simplest case is to have one environment. One could also have one environment per branch, such that you can deploy your changes on a “development” branch to a test server and you can deploy changes on the “master” branch to the production server.

  6. Now, every time you have changes you’d like to commit, simply execute:
    eb deploy
  7. If you wish to view the application online, you can execute:
    eb open

That’s it! If you have any questions or remarks, feel free to post them in the comment section below.