Deploying an Auto Scaling Flask app with Elastic Beanstalk

If you SSH into an EC2 instance you will see the hostname is something like: ec2-user@ip-172-31-42-219.

As a hacky but fun project, we can make a simple Flask app to get an idea of what is going on under the hood. Elastic Beanstalk is nice because it creates the EC2 instances, load balancer, security groups, S3 bucket, auto scaling group, and Cloudwatch alarms for you in one command.

In our Flask route we can use the os.uname 5 tuple to grab the nodename, and we can then strip the leading 3 characters and convert the IP address to dot notation. Lastly we can render the 'ip' variable in our template with Jinja, and visitors to the page can see the IP address of each EC2 instance behind the load balancer.

You can find the project and clone it from my repo here.

If you're using Python you can just pip install awsebcli, otherwise you'll want to follow the docs on how to set up your EB CLI.

You can pip install -r requirements.txt, and once you're ready to deploy, specify the number of instances you'd like to see with eb create --scale integer, and eb open when your environment is ready.

When you're finished, clean up your environment with eb terminate flask_elastic_beanstalk.

Some other helpful Elastic Beanstalk commands are:
  • eb status
  • eb health
  • eb deploy
  • eb events
  • eb terminate