Hosting is a consistent stumbling block that most beginners face when setting up a new Flask application, and in this article, we’ll help you overcome it step by step. Use this guide to learn the basics of developing and deploying a Flask app on the popular AWS and Heroku cloud application platforms.
Hire the best developers in Latin America. Get a free quote today!
Contact Us Today!Flask is a web application framework written in Python. Flask has many cool features like URL routing, a template engine, etc. These features let you develop web applications easily. The Flask framework is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both projects are maintained by a team of international Python enthusiasts called Poocco.
AWS (Amazon Web Services) provides information technology infrastructure services to businesses in the form of web services. Its products and solutions include cloud computing, compute, networking, storage and content delivery, databases, analytics, application services, deployment and management, gaming, digital media, as well as backup and recovery services. AWS is based in Seattle, Washington, United States and it has data center locations spread across the United States, Europe, Brazil, Singapore, Japan, Africa, and Australia.
Heroku is a container-based cloud Platform as a Service (PaaS). Developers use Heroku to deploy, manage, and scale modern applications. It uses language-specific build packs and is thus able to host applications written in any language. Heroku was first deployed in 2007 and it has since grown to be a key player in the cloud industry, today offering a wide range of products and services.
In this guide, you’ll learn how to:
This guide assumes that you understand the basics of Flask web development and that you have some experience using Git.
Prerequisites
Before starting this guide, you should have:
The following steps demonstrate the basic developer flow for creating a Flask web application and hosting it on AWS’s Elastic Beanstalk service. Elastic Beanstalk is a service for deploying and scaling web applications and services. When you push your code, Elastic Beanstalk automatically handles the end-to-end deployment—from capacity provisioning, load balancing, auto scaling, down to application health monitoring.
We are assuming that you do not have a pre-existing AWS account with Amazon (in case you do then please feel free to skip this section). Amazon Web Services (AWS) provides a 12-month limited fully functional free account which can be used to learn the different components of AWS. With this account, you get access to many services provided by AWS although there are some services that are unavailable on the free-tier. To create an AWS account:
$ git clone https://github.com/aws/aws-elastic-beanstalk-cli-setup.git
$ python ./aws-elastic-beanstalk-cli-setup/scripts/ebcli_installer.py
$ python .\aws-elastic-beanstalk-cli-setup\scripts\ebcli_installer.py
After installation on Linux and macOS, the output contains instructions on how to add the EB CLI (and Python) executable file to the shell’s $PATH variable, if it isn’t already in it.
In this step, you’re going to set up a virtual environment that will help you isolate the Flask application from the other Python files on your system.
$ sudo apt install python3-venv
$ mkdir ~/awsproject
$ cd ~/awsproject
$ python3 -m venv awsprojectenv
This will install a local copy of Python and pip into a directory called awsprojectenv within your project directory.
$ source awsprojectenv/bin/activate
Your prompt will change to indicate that you are now operating within the virtual environment. You will see (awsprojectenv) prepended to your command prompt, indicating that you’re in a virtual environment, for example: (awsprojectenv)user@host:~/awsproject$.
Now that you are in your virtual environment, you can get started on building a Python application using the Flask microframework.
$ pip install wheel
$ pip install flask==2.0.3
$ pip freeze
click==8.1.1
Flask==2.0.3
itsdangerous==2.1.2
Jinja2==3.1.1
MarkupSafe==2.1.1
Werkzeug==2.1.0
This command lists all of the packages installed in your virtual environment. Because you are in a virtual environment, globally installed packages like the EB CLI are not shown.
$ pip freeze > requirements.txt
This file tells Elastic Beanstalk to install the libraries during deployment.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<h1 style='color:green'>Hello World!</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0')
Flask is a microframework that exists as a Python module. The example above will import the Flask module and instantiate a Flask object. You can use this to define the functions that should be run when a specific route is requested.
$ python app.py
* Serving Flask app "myproject" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
When you are finished, hit CTRL-C
in your terminal window to stop the Flask development server.
If you got debug output instead, fix the errors and make sure the application is running locally before proceeding to the next steps.
You now have everything you need to deploy your application on AWS Elastic Beanstalk. Your project directory should now look like this:
~/awsproject/
├── awsprojectenv
├── app.py
└── requirements.txt
awsprojectenv
folder is not required for the application to run on Elastic Beanstalk. When you deploy, Elastic Beanstalk creates a new virtual environment on the server instances and installs the libraries listed in requirements.txt
. To minimize the size of the source bundle that you upload during deployment, add an .ebignore
file that tells the EB CLI
to leave out the awsprojectenv folder. Create a new text file in this directory named .ebignore
with the following contents: awsprojectenv
EB CLI
repository with the eb init
command: $ eb init -p python-3.7 flask-app --region us-west-2
Output:
Application flask-app has been created.
This command creates a new application named flask-app and configures your local repository to create environments with the latest Python 3.7
platform version.
eb init
again to configure a default keypair so that you can connect to the EC2 instance running your application with SSH
: $ eb init
Select a key pair if you have one already, or follow the prompts to create a new one.
eb create
: $ eb create flask-env
Environment creation takes about 5 minutes and creates the following resources:
port 80
.subdomain.region.elasticbeanstalk.com
.eb open
: $ eb open
This will open a browser window using the domain name created for your application. You should see the same Flask website that you created and tested locally.
Once you get to this point, you can terminate all the AWS resources that you provisioned in your environment, (i.e.) Amazon EC2 instances, database instances, load balancers, security groups, and alarms.
To terminate your Elastic Beanstalk environment, run the following command:
$ eb terminate flask-env
In this section, you’ll create a Python Flask example application and deploy it to Heroku, making it publicly available on the web. Heroku removes much of the infrastructure burden related to building and running web applications, allowing you to focus on creating awesome applications. Some of the abstractions handled by Heroku include:
Throughout the rest of this section, you’ll learn how to deploy the previously created web application to the internet using Heroku. By the end of this section, your application will be publicly available under a nice URL and served using HTTPS.
Heroku, being a Software as a Service (SaaS) offering, requires you to create an account and login before you can start using its platform. Therefore, before we get started, you should first sign-up for a Heroku account. You can create an account at this URL:
The Heroku Command Line Interface (CLI) lets you create, manage and scale applications, provision add-ons, view your application logs, and run your application locally directly from the terminal. It’s an essential part of using Heroku.
Install the appropriate version of the Heroku CLI for your respective OS as follows:
Windows:
Download the appropriate installer for your Windows installation:
macOS:
$ brew tap heroku/brew && brew install heroku
Linux:
$ curl https://cli-assets.heroku.com/install.sh | sh
To verify your CLI installation, use the heroku –version command:
$ heroku --version
Output:
The output looks like heroku/x.y.z
.
After you install the CLI, run the heroku login command. Enter your login credentials to complete login.
$ heroku login -i
heroku: Enter your login credentials
Email: me@example.com
Password: ***************
Two-factor code: ********
Logged in as me@heroku.com
The CLI logs you in automatically and saves your email address. An API token to ~/.netrc
for future use.
In this step, you’ll set up a virtual environment that will isolate the Flask application from the other Python files on your sysystem.
python3-venv
package, which will install the venv
module: $ sudo apt install python3-venv
$ mkdir ~/herokuproject
$ cd ~/herokuproject
$ python3 -m venv herokuprojectenv
This will install a local copy of Python and pip into a directory called herokuprojectenv within your project didirectory.
$ source herokuprojectenv/bin/activate
Your prompt will change to indicate that you are now operating within the virtual environment. You will see (herokuprojectenv)
prepended to your command prompt, indicating that you’re in a virtual environment. something like this: (herokuprojectenv)user@host:~/herokuproject$
.
Now that you are in your virtual environment, it’s time to prepare a simple Flask application for deployment, i.e. one that consists of just app.py
.
$ pip install wheel
$ pip install flask==2.0.3
python app.py
from our command-line, we’re running the default webserver that comes with Flask. However, Heroku seems to prefer a web server called gunicorn. Just so that we can follow along with Heroku’s documentation, let’s install gunicorn on our own system. It’s a Python library like any other and can be installed with pip
: $ pip install gunicorn
$ pip freeze
click==8.1.1
Flask==2.0.3
itsdangerous==2.1.2
Jinja2==3.1.1
MarkupSafe==2.1.1
Werkzeug==2.1.0
gunicorn==20.0.1
This command lists all of the packages installed in your virtual environment. Because you are in a virtual environment, globally installed packages like the Heroku CLI are not shown.
pip freeze
to a file named requirements.txt
. $ pip freeze > requirements.txt
This file tells Heroku to install the libraries during deployment.
app.py
and paste the following code: from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<h1 style='color:green'>Hello World!</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0')
The example above will import the Flask module and instantiate a Flask object. You can use this to define the functions that should be run when a specific route is requested.
10. Save and close the file when you’re finished.
11. Now you can test your Flask app by running the following command:
$ python app.py
12. You will see the following output, including a helpful warning reminding you not to use this server setup in production:
Output:
* Serving Flask app "myproject" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
13. Open http://127.0.0.1:5000/ in your web browser to view your web application.
When you are finished, hit CTRL-C in your terminal window to stop the Flask development server.
If you got debug output instead, fix the errors and make sure the application is running locally before proceeding to the next steps.
With Heroku, we have to include some metadata with our application code, so that Heroku knows how to set up a compatible webserver and install the software that our application needs.
--version
flag to reveal which version of Python you are running: $ python --version
Python 3.7.1 :: Anaconda 2.5.0 (x86_64)
python-3.7.1
web: gunicorn app:app --log-file=-
.gitignore
file to prevent unwanted files from being pushed up to Heroku Git repo (or any git repo) later on. Create a new file named .gitignore
and copy the contents of the example .gitignore
file here:https://github.com/github/gitignore/blob/master/Python.gitignore
$ heroku local web
The command creates an app at http://localhost:5000, which should work like before when you ran python app.py
.
So by now our simple Flask app folder contains this file structure:
~/herokuproject/
├── .gitignore
├── herokuprojectenv
├── Procfile
├── app.py
├── requirements.txt
└── runtime.txt
We need to set up a git repo for this project because Heroku deploys using git—which is not to be confused with GitHub or GitLab. Basically, this means before we can deploy to Heroku, we need to create a git repo in our app, add the files, and commit them. But we don’t need to push them onto a GitHub repo if we don’t want to.
In fact, for this basic app, don’t bother making a GitHub repo. Just make a local git repo:
$ git init
$ git add .
$ git commit -m 'first'
OK, now Heroku has all it needs to provision a server for our application.
Now we need to tell Heroku to initialize an application via its create command. Create an app on Heroku, which prepares Heroku to receive your source code:
$ heroku create
Creating app... done, ⬢ serene-caverns-93825
https://misty-caverns-93825.herokuapp.com/ | https://git.heroku.com/misty-caverns-93825.git
When you create an app, a git remote (called heroku) is also created and associated with your local git repository.
Heroku generates a random name (in this case misty-caverns-93825) for your app, or you can pass a parameter to specify your own app name.
That output tells us two things:
Finally it’s time to push your Flask code to Heroku.
$ git push origin master
This should seem familiar to when you’ve pushed code to your Github account, but targeting origin master. We haven’t actually created a Github git repo for our simple app—we’ve only created a local repo.
$ git push heroku master
And with that simple command, Heroku will go through the steps of taking our application code, installing the dependencies we specified in requirements.txt and runtime.txt, and then starting a webserver as specified in Procfile. After about 30 seconds, you’ll get output telling you how to find your application on the web.
$ heroku open
Et voilà! You now have a functioning Python + Flask application deployed on Heroku.
To delete the deployed version of your app and the reserved URL—but not your local code—you can use the apps:destroy
subcommand:
$ heroku apps:destroy whatever-yourappnameis-12345
Do you have any questions or got stuck at any part of the process? Please leave a comment below and I will help you out. I hope this guide has been clear enough so now you can up and running deploying a bunch of Flask apps on AWS and Heroku! Happy coding!
Digital transformation of business operations worldwide is driving demand for technically talented workers. However, organizations…
This post provides readers with a framework for evaluating Next Idea Tech's potential financial impact…
Generative AI promises to rewrite the way software is built and maintained and technology leaders…
A nearshore LatAm Development Centre is a dedicated facility located in Latin America that as…
Building a software development team, regardless of location, presents its own unique challenges. The prospect…
Outsourcing software developers from LatAm can be a real game-changer for fast-growing small and medium-sized…
This website uses cookies.