Django and Elastic Beanstalk, a Great Combination

Django and Elastic Beanstalk, a Great Combination
Photo by Tijana Drndarski / Unsplash

This post shows a 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 initYou 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:

    command: "touch db.sqlite3 && chmod 0777 db.sqlite3"
    command: "mkdir static && chmod 0777 static && chmod 0777 ."
    command: " collectstatic --noinput"
    command: " compilemessages --locale nl"
    command: " migrate --noinput"
    leader_only: true
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

    DJANGO_SETTINGS_MODULE: "myapp.settings"
    WSGIPath: "myapp/"

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

  1. You need an environment to deploy your changes to. For this, you should execute the following command:eb create my-envHere, “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.
  2. Now, every time you have changes you’d like to commit, simply execute:eb deploy
  3. 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.