Launching a Django Project on Amazon Web Services (AWS) Elastic Beanstalk.
-
Setup Virtual Environment, GIT, & Django. Create Virtualenv
cd ~/Desktop virtualenv awsbean && cd awsbeanActivate Virtualenv
Mac/ Linux :
source bin/activateWindows:
.\Scripts\activateInitialize Git (need to install it?) inside of your
virtualenv.git initCreate gitignore (Mac/Linux)
touch .gitignore open .gitignoreCreate gitignore (Windows)
- Download and Install Sublime Text -- Free version works fine. Or any other code text editor.
- Open
Sublime Text(or your code text editor) File>New FileFile>Save- Save the file as
.gitignore(not the.prior.) into your newly created virtualenv
Add & Save the following to your newly created
.gitignorefile:bin/ include/ lib/ *.py[cod] *.sqlite3 pip-selfcheck.jsonInstall Django & Start Project:
pip install django==1.8.7 django-admin.py startproject awsbean -
Install AWS Command Line Interface:
Ensure virtualenv is activated
cd /path/to/root/of/your/virtualenv/ source bin/activate # if Mac/Linux .\Scripts\activate * if WindowsInstall AWS CLI
pip install awsebcliTest installation
eb --versionReturns something like
EB CLI 3.6.1 (Python 2.7.9) -
Git Commit
git add . git commit -m "first commit" -
Create AWS User Credentials
-
Navigate to IAM Users
-
Select
Create New Users -
Enter
awsbeanas a username (or whatever you prefer) -
Ensure
Generate an access key for each useris selected. -
Select
Download credentialsand keep them safe. -
Open the
credentials.csvfile that was just downloaded/created -
Note the
Access Key IdandSecret Access Keyas they are needed for a future step. These will be referred to as<your_access_key_id>and<your_secret_access_key>
-
-
Create Elastic Beanstalk Application via Command Line (aka Terminal/Command Prompt) ** Ensure virtualenv is activated **
cd /path/to/root/of/your/virtualenv/ source bin/activate # if Mac/Linux .\Scripts\activate * if WindowsInitialize EB:
eb initThis will respond with a few prompts you need to answer. Here's what we did:
Select a default region 1) us-east-1 : US East (N. Virginia) 2) us-west-1 : US West (N. California) 3) us-west-2 : US West (Oregon) 4) eu-west-1 : EU (Ireland) 5) eu-central-1 : EU (Frankfurt) 6) ap-southeast-1 : Asia Pacific (Singapore) 7) ap-southeast-2 : Asia Pacific (Sydney) 8) ap-northeast-1 : Asia Pacific (Tokyo) 9) sa-east-1 : South America (Sao Paulo) 10) cn-north-1 : China (Beijing) (default is 3): 3 # this is our answer You have not yet set up your credentials or your credentials are incorrect You must provide your credentials. (aws-access-id): <your_access_key_id> (aws-secret-key): <your_secret_access_key> Select an application to use 1) [ Create new Application ] (default is 1): 1 # We created a new one Enter Application Name (default is "awsbean"): # We pressed enter to use the default Application awsbean has been created. Select a platform. 1) Node.js 2) PHP 3) Python 4) Ruby 5) Tomcat 6) IIS 7) Docker 8) Multi-container Docker 9) GlassFish 10) Go 11) Java (default is 1): 3 # Select 3 for Python. Select a platform version. 1) Python 3.4 2) Python 3) Python 2.7 4) Python 3.4 (Preconfigured - Docker) (default is 1): 3 # Select 3 for 2.7 if that is what you use locally Do you want to set up SSH for your instances? (y/n): y # Optional, not needed at this point. Select a keypair. 1) aws-eb 2) aws-eb2 3) [ Create new KeyPair ] # If you said yes to SSH, this is required.Create Elastic Beanstalk with Database Option
eb create -dbThe
-dboption creates aMySQLdatabase for us by default which makes setup a lot easier. More create options are here.Now, we are prompted with:
Enter Environment Name (default is awsbean-dev): Enter DNS CNAME prefix (default is awsbean-dev): Enter an RDS DB username (default is "ebroot"): Enter an RDS DB master password: Retype password to confirm:Fill out those settings as you'd like. Take note of the master password you set.
Set default environment in elastic beanstalk. The environment name is what we entered during the
eb create -dbprocess.eb use awsbean-dev -
Django Production
settings.py:- These credentials are needed for deployment*
- In many cases, you will have a
productionversion of yoursettings.pyinstead of the defaultDjangoinstall.
AWS_ACCESS_KEY_ID = "<your_access_key_id>" AWS_SECRET_ACCESS_KEY = "<your_secret_access_key>"if 'RDS_DB_NAME' 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'], } } -
Setup EB Extensions:
- Create new folder called
.ebextensionsin the root of your virtualenv where the.elasticbeanstalkdirectory is as well. - Add a new file called
01_awsbean.configin.ebextensionswith contents of:
option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "awsbean.settings" PYTHONPATH: "/opt/python/current/app/src:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "src/awsbean/wsgi.py"Note:
awsbeanabove will be replaced with your app name.- Add a new file called
02_packages.configin.ebextensionswith contents of:
packages: yum: git: []- Add a new file called
03_python.configin.ebextensionswith contents of:
container_commands: 01_migrate: command: "python src/manage.py migrate --noinput" leader_only: true- Commit in git:
git add .ebextensions/ git commit -m "Created EB Extensions" - Create new folder called
-
Add Django Requirements Everytime you add new python packages, such as the
Django Rest FrameworkorRequests, you need to update and commit your requirements.Install MySQL-python
pip install MySQL-pythonUpdate (or create)
requirements.txtpip freeze #returns what packages are required/installed in your virtualenv. pip freeze > requirements.txt git add requirements.txt git commit -m "Updated requirements.txt" -
1st Deploy to Elastic Beanstalk Do Deployment:
eb deployReturns something like:
Creating application version archive "app-903f-151207_174054". Uploading awsbean/app-903f-151207_174054.zip to S3. This may take a while. Upload Complete. INFO: Environment update is starting. INFO: Deploying new version to instance(s). INFO: New application version was deployed to running EC2 instances. INFO: Environment update completed successfully. -
Create Superuser with Custom Management Nice! We have deployed Django to elastic beanstalk! Great work. Now how do we create a superuser? Run collect static? This is when we need to add a few more customizations to the
.ebextensionsfolder.-
Create a new Django App
cd src python manage.py startapp accounts cd accounts mkdir management cd management touch __init__.py mkdir commands cd commands touch __init__.py touch makesuper.py open makesuper.py -
Create the
makesuperCommand inside themakesuper.pyfile we just created:from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): User = get_user_model() if not User.objects.filter(username="superu").exists(): User.objects.create_superuser("superu", "superu@teamcfe.com", "superuPASS")This code checks if the
superuexists and creates it if it doesn't. -
Add the new
accountsapp toINSTALLED_APPSinsettings.py -
Now, we can use
python manage.py makesuperwhich will automatcially create a Django super user with the usernamesuperuand passwordsuperuPASS-- this means we can login to the Django admin. -
Add new additions to git:
git add --all git commit -m "Makesuper command & Accounts App" -
Create new EB Extension: Add
04_python.configto.ebextensionsfolder with the following:container_commands: 01_migrate: command: "python src/manage.py makesuper" leader_only: true -
Add new eb ebextension to git:
git add --all git commit -m "Updated Eb Extensions"
-
-
Deploy!
eb deploy
Subscribe on our YouTube Channel and join us for more in-depth tutorials on Django development.
Cheers!