Flask on Azure Deployment

by Kal Bartal

Introduction

Are you ready to build a Flask app and deploy it to Azure App Service? Flask is a popular Python web framework that allows you to build lightweight and scalable web applications. By the end of this tutorial, you’ll have a Flask app running on Azure App Service.

Setting up a Flask application

1.1 Installing Flask and its dependencies

Flask is a Python web framework that allows you to build web applications quickly and easily. Before installing Flask, you need to make sure you have Python installed on your computer. You can download Python from the official Python website.

Once you have Python installed, you can install Flask and its dependencies using pip, which is the package installer for Python. To install Flask, simply open a terminal or command prompt and type:

pip install flask

This will download and install the latest version of Flask and its dependencies. Depending on your system, you may need to run this command with administrator privileges by adding sudo before the command on Unix-based systems, or by running the command prompt as an administrator on Windows.

Once Flask is installed, you can check that it was installed correctly by running the following command:

python -c "import flask; print(flask.__version__)"

This will print the version number of Flask that was installed.

1.2 Creating a basic Flask app

To create a basic Flask app, you need to create a Python file with the .py extension and import the Flask module. Here is an example of a basic Flask app:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

In this example, we first import the Flask module, and then create a new instance of the Flask class with the name of the application as the argument. We then define a route for the root URL / using the @app.route decorator, and define a function to handle that route. The function simply returns the string ‘Hello, World!’ as a response.

To run the app, save this code in a file with the .py extension, such as app.py. Then, from a terminal or command prompt, navigate to the directory where the file is saved and run the following command:

flask run

This will start a local development server, and you should see output that the app is running. You can then visit the URL http://127.0.0.1:5000 in your web browser, and you should see the message ‘Hello, World!’

You now have a basic Flask app running on your local machine. You can modify the app by adding more routes and functions to handle those routes, as well as HTML templates and other features.

1.3 Testing the Flask app locally

After you have created your Flask app, you can test it locally to make sure everything is working as expected before deploying it to Azure. To test your Flask app, you can simply run it locally using the flask run command. Here are the steps:

  • Open a terminal or command prompt and navigate to the directory where your Flask app file is located.
  • Set the FLASK_APP environment variable to the name of your app file. For example, if your app file is named app.py, you can set the FLASK_APP environment variable by running the following command:
export FLASK_APP=app.py

Run the flask run command to start the development server. This command will start the Flask app on a local web server and display a URL where you can access it. For example:

flask run
* Running on http://127.0.0.1:5000/
  • Open a web browser and go to the URL displayed in the output. You should see your Flask app running in the browser.

You can now test your Flask app by interacting with it in the web browser. Try clicking any links, submitting forms, or interacting with any other elements to ensure everything is working as expected.

You’ve now tested your Flask app locally and verified that it’s working correctly. You can make any necessary changes to the code, test them locally, and then proceed to deploy your app to Azure.

1.4 Creating and activating a virtual environment for the Flask app

Before deploying your Flask app, it’s a good practice to create and activate a virtual environment for it. This isolates the dependencies required by the app from those installed globally on your machine, and allows you to easily manage them.

To create and activate a virtual environment, follow these steps:

  1. Open a terminal window and navigate to your Flask app directory.
  2. Install the virtualenv package if you don’t have it installed already, by running pip install virtualenv.
  3. Create a virtual environment by running virtualenv venv.
  4. Activate the virtual environment by running source venv/bin/activate on macOS/Linux, or venv\Scripts\activate on Windows.

Once the virtual environment is activated, any packages you install using pip will be installed in the virtual environment, and won’t affect your global Python environment. You can deactivate the virtual environment by running deactivate at any time.

1.5 Creating a requirements.txt file

Before deploying the Flask app to Azure App Service, it’s a best practice to create a requirements.txt file which lists all the dependencies required by the app. This file can be used by Azure App Service to automatically install all the necessary dependencies in the production environment.

To create a requirements.txt file, activate the virtual environment created in step 1.4 and run the following command:

pip freeze > requirements.txt

This command will generate a requirements.txt file containing all the dependencies and their respective versions. Make sure to commit this file to Git along with the Flask app code so that it’s included in the deployment package.

Creating an Azure App Service

2.1 Creating an Azure account

To create an Azure account, you need to go to the Azure website and sign up for a new account. Here are the steps:

  1. Go to the Azure website at https://azure.microsoft.com/.
  2. Click on the “Start free” button in the top right corner of the page.
  3. Sign in with your Microsoft account or create a new one.
  4. Follow the prompts to set up your account, including selecting a subscription type, entering billing information (if necessary), and verifying your identity.

Once you’ve completed the sign-up process, you will have access to the Azure portal, which is where you can manage all of your Azure resources, including the Azure App Service that we’ll be using to deploy our Flask app.

2.2 Creating an App Service resource

To create an App Service resource for hosting a Flask application, you’ll want to create a Web App. Here are the steps to create a Web App:

  1. Go to the Azure portal at https://portal.azure.com/.
  2. Click on the “Create a resource” button in the top left corner of the page.
  3. Search for “Web App” in the search bar and select “Web App” from the list of results.
  4. Click the “Create” button to start the Web App creation process.
  5. In the “Basics” tab of the creation wizard, configure the following settings:
    • Subscription: select the subscription you want to use.
    • Resource group: create a new resource group or select an existing one.
    • Name: enter a unique name for your Web App. This will be part of the URL used to access your app.
    • Publish: select “Code” to deploy your Flask app from a Git repository or from a local Git repository.
    • Runtime stack: select “Python” as the runtime stack.
    • Operating System: select “Linux” or “Windows” depending on your preferences and requirements.
    • Region: select the region where you want to deploy your Web App.
  6. Click the “Next: Monitoring” button to configure monitoring and diagnostic settings for your Web App. You can skip this step if you want to configure these settings later.
  7. Click the “Next: Tags” button to configure tags for your Web App. You can skip this step if you want to configure tags later.
  8. Click the “Review + create” button to review your settings and create the Web App.
  9. Review your settings, and click the “Create” button to create the Web App.

Azure will now create your Web App, which may take a few minutes to complete. Once the Web App is created, you can proceed to configure the App Service settings, which we’ll cover in the next section.

2.3 Configuring the App Service settings

After you have created your Web App, you can configure the App Service settings to set up your Flask application for deployment. Here are the steps:

  1. Sign in to the Azure portal at https://portal.azure.com/.
  2. Navigate to the “App Service” blade and select the Web App that you want to configure.
  3. In the “Overview” tab, click on the “Configuration” button to access the App Service configuration settings.
  4. In the “General settings” section, configure the following settings:
    • Startup Command: if necessary, specify the startup command for your Flask application. For example, if your Flask application is defined in a file named app.py, you can specify the startup command as gunicorn app:app. This tells the server to start the Gunicorn WSGI server with the app object defined in the app.py file.
    • Python version: select the version of Python that you want to use for your Flask application. The latest version of Python is recommended.
    • Always On: select “On” if you want to keep your Flask app running continuously, even when there is no traffic.
  5. In the “Application settings” section, configure any environment variables or application settings that your Flask app needs to run. You can add environment variables by clicking the “Add new setting” button and entering a name and value for each variable.
  6. Click the “Save” button to save your changes.

The App Service settings for your Flask application are now configured. You can now deploy your Flask app to the App Service using Git.

Deploying the Flask app to Azure App Service

3.1 Using Git to deploy the app

To deploy your Flask app to the App Service using Git, you need to set up a Git repository for your app and then configure the App Service to deploy the app from that repository. Here are the steps:

  1. Create a Git repository for your Flask app. You can use a service like GitHub or GitLab, or you can create a local Git repository on your computer. Make sure that the repository contains all of the necessary files and dependencies for your Flask app.
  2. In the Azure portal, navigate to the “Deployment Center” tab of your Web App.
  3. Select “GitHub” or “Local Git” as the deployment source, depending on where your Git repository is located.
  4. Follow the prompts to connect your Git repository to your App Service.
  5. Once your Git repository is connected, select the branch that you want to deploy from and configure any deployment options, such as continuous deployment or manual deployment.
  6. Click the “Save” button to save your changes.

Azure will now deploy your Flask app to the App Service using Git. You can monitor the deployment process in the “Deployment Center” tab of your Web App.

You’ve now deployed your Flask app to the App Service using Git. You can now access your app by going to the URL of your Web App, which should be listed in the “Overview” tab of your Web App in the Azure portal.

3.2 Setting up deployment credentials

In order to deploy your Flask app to Azure App Service using Git, you need to set up deployment credentials. This will allow you to securely push code changes to the Azure App Service.

Here are the steps to set up deployment credentials:

  1. Navigate to the Azure portal and select your App Service.
  2. In the left-hand menu, under Deployment, select Deployment Center.
  3. Select the External option and choose Git.
  4. Select App Service build service as the build provider.
  5. Under Continuous Deployment, select the deployment option that works best for you.
  6. Select the App Service build service option as the build provider.
  7. In the Deployment Credentials section, click the Add button.
  8. Enter a username and password to use for the deployment credentials.
  9. Click Save to save the credentials.

Once you have set up deployment credentials, you can use them to push your Flask app to Azure App Service using Git.

3.3 Deploying the app using Git
  1. Open the App Service resource in the Azure portal.
  2. Click on “Deployment Center” in the left-hand menu.
  3. Choose “GitHub” as the source control option.
  4. Follow the prompts to authorize Azure to access your GitHub account and select the repository that contains your Flask app.
  5. Configure the deployment options, such as the branch to use and any custom deployment scripts.
  6. Click “Save” to save the deployment options.
  7. Click “Deployment Center” again to return to the main Deployment Center page.
  8. Click the “Refresh” button to refresh the status of the deployment.
  9. Wait for the deployment to complete, which can take several minutes depending on the size of your app and any dependencies that need to be installed.
  10. Once the deployment is complete, open your app in a web browser to verify that it is running on Azure.

Note that if you’re using a different source control provider, the exact steps may differ slightly, but the general process of configuring the deployment center and waiting for the deployment to complete should be similar.

3.4 Verifying the app is running on Azure

After deploying the Flask app to Azure App Service, it is important to verify that the app is running correctly on the Azure platform. Here are the steps to verify the app:

  1. In the Azure portal, navigate to the App Service that you just deployed the app to.
  2. Click on the “URL” link under the “Overview” section to open the app in a web browser.
  3. Verify that the app is running correctly by interacting with it in the web browser. If the app displays as expected and functions correctly, then it is running correctly on Azure.

If there are any issues with the app on Azure, check the app logs to identify the issue and resolve it. You can access the app logs by going to the “Log stream” tab under the “Monitoring” section of the App Service in the Azure portal.

Scaling and monitoring the app on Azure App Service

4.1 Scaling up or down the App Service plan

In Azure App Service, you can scale up or down your App Service plan, which is the set of compute resources that run your app. Scaling up or down your App Service plan can improve the performance and scalability of your app.

Here are the steps to scale up or down your App Service plan:

  1. Go to the Azure portal and navigate to your App Service resource.
  2. In the left menu, click on “Scale up (App Service plan)”.
  3. In the “Scale up” page, select the pricing tier you want to scale to.
  4. Click the “Apply” button at the top of the page to save the changes.

Note that when you scale up your App Service plan, you will also increase the cost of running your app. Therefore, you should carefully consider the performance and cost implications before scaling up your App Service plan.

4.2 Enabling Application Insights for monitoring

To enable Application Insights for monitoring your app on Azure App Service, follow these steps:

  1. Go to the Azure portal and navigate to your App Service resource.
  2. In the left-hand menu, select “Application Insights” under the Monitoring section.
  3. Click the “Turn on Application Insights” button and follow the prompts to create a new Application Insights resource or link an existing one.
  4. Once the Application Insights resource is created and linked, you can access it by clicking on the “Application Insights” tab in the left-hand menu of your App Service resource.
  5. From there, you can view a dashboard of your app’s performance metrics, such as request volume, response times, and error rates. You can also set up alerts and custom queries to monitor specific aspects of your app’s behavior.

Note that enabling Application Insights may incur additional costs, so be sure to review the pricing information before enabling it for your app.

4.3 Viewing application performance metrics

To view the performance metrics of your application in Azure, follow these steps:

  1. Go to the Azure portal and navigate to your App Service resource.
  2. In the left-hand menu, under the Monitoring section, click on “Metrics”.
  3. Select the “Performance” tab.
  4. Select the desired time range for the metrics.
  5. Choose the metric you want to view, such as “CPU time” or “Memory working set”.
  6. Click on “Apply” to see the metrics for the selected time range.
  7. You can also create a chart to compare different metrics or add custom metrics.

In addition, you can also set up alerts for your application’s performance metrics, so you can be notified when certain thresholds are exceeded. To do this, click on the “Alerts” option in the Monitoring section of your App Service resource, and then follow the instructions to create an alert rule based on your chosen metric and threshold.

Conclusion

By following the steps in this tutorial, you will have learned how to deploy a Flask app on Azure App Service. You can use this as a starting point for building more complex web applications on Azure, and you can customize the App Service settings to match your specific needs and scale up or down as your traffic demands change.

UPDATE! The full code with tweaks and bug fixes is available on my GitHub.

Related Posts

Leave a Comment