Skip to content

Deployment via Amazon Elastic Beanstalk

Stanislav Valasek edited this page Dec 5, 2020 · 10 revisions

Input sources

How to deploy Django to AWS using Elastic Beanstalk

Install AWS CLI

pip install awsebcli

ASW Deployment

mkdir .ebextensions

Create .ebextensions\django.config with content

container_commands:
    01_sh_executable:
        command: find .platform/hooks/ -type f -iname "*.sh" -exec chmod +x {} \;
option_settings:
    aws:elasticbeanstalk:application:environment:
        DJANGO_SETTINGS_MODULE: ebdjango.settings
    aws:elasticbeanstalk:environment:proxy:staticfiles:
        /static: static
        /static_files: static_files
    aws:elasticbeanstalk:container:python:
        WSGIPath: ebdjango.wsgi:application

Run the commands

eb init -p python-3.7 kicoma
eb create kicoma-env
eb status

set CNAME value CNAME: kicoma-env.eba-j2q4pbqw.eu-central-1.elasticbeanstalk.com

eb setenv PYTHONHASHSEED=random WEB_CONCURRENCY=4 DJANGO_DEBUG=False DJANGO_SETTINGS_MODULE=config.settings.production
eb setenv DJANGO_SECRET_KEY="$(openssl rand -base64 64)"
# Generating a 32 character-long random string without any of the visually similar characters "IOl01":
eb setenv DJANGO_ADMIN_URL="$(openssl rand -base64 4096 | tr -dc 'A-HJ-NP-Za-km-z2-9' | head -c 32)/"
# Set this to your CNAME value, e.g. 'kicoma-env.eba-j2q4pbqw.eu-central-1.elasticbeanstalk.com'
eb setenv DJANGO_ALLOWED_HOSTS=kicoma-env.eba-primifzb.eu-central-1.elasticbeanstalk.com
eb setenv MAILGUN_API_KEY=<API key> MAILGUN_API_URL=<API url> MAILGUN_DOMAIN=<domain>

Create .platform/hooks/predeploy/01_migrations.sh with a content

container_commands:
    01_sh_executable:
        command: find .platform/hooks/ -type f -iname "*.sh" -exec chmod +x {} \;
option_settings:
    aws:elasticbeanstalk:application:environment:
        DJANGO_SETTINGS_MODULE: config.settings.production
    aws:elasticbeanstalk:environment:proxy:staticfiles:
        /static: static
        /static_files: static_files
    aws:elasticbeanstalk:container:python:
        WSGIPath: ebdjango.wsgi:application

Comment out CACHES = {... in settings/production.py or configure Redis on AWS and set REDIS_URL

Add a DB

Update settings file

import os

if 'RDS_HOSTNAME' in os.environ:
    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'],
        }
    }

Deploy

eb deploy or eb deploy --staged to deploy from git stage

Further resources

https://stackoverflow.com/questions/64696380/aws-elastic-beanstalk-django-application-health-check-problem