Azure Container Apps present cost-effective, scalable, and absolutely managed app providers using a Kubernetes-based platform. A containerized utility picture, comparable to one created with Docker, can simply be deployed with a minimal quantity of administration required to run the appliance on the cloud. Many of the heavy lifting is managed by Azure, providing scalability at a manageable value.
The scalable value choice is good for intranet-based purposes the place a lot of the consumption happens internally, with customers interacting with the appliance in a fashion much like how they might with PowerBI or Tableau providers. Nevertheless, not like PowerBI or Tableau, internet hosting an information internet utility provides the benefit of not requiring consumer license prices, together with the flexibleness to beat limitations of those dashboarding instruments. When mixed with the convenience of growth in Python, powered by frameworks comparable to Plotly Sprint, it presents a robust various to different dashboarding options.
Plotly is a well-liked knowledge visualization framework, out there in a number of programming languages comparable to Python, R, JavaScript, and Matlab. Sprint, developed by Plotly, is a framework for constructing extremely interactive knowledge purposes. It employs a Python Flask server and makes use of React for constructing interactive internet purposes, enabling customers to develop knowledge purposes completely in Python. Moreover, it provides the flexibleness to combine customized HTML/CSS/JavaScript parts as wanted.
Though options like Streamlit exist for constructing knowledge analytics purposes in Python, this text will particularly cowl Sprint because of its use of Python Flask for backend providers. Sprint’s utilization of Flask offers vital flexibility, permitting for varied purposes to coexist on the identical web site. For instance, sure sections of an app could possibly be constructed utilizing pure HTML/CSS/JavaScript or React, whereas others may incorporate embedded PowerBI experiences.
Sprint is accessible in two flavors: open supply and enterprise. We’ll concentrate on the open-source model, addressing its limitations comparable to safety administration, which could be enhanced via the usage of a customized Flask server.
Python’s Flask library is a light-weight but highly effective internet framework. Its light-weight design is especially suited to knowledge analytics professionals who might not have intensive internet growth expertise and like to start out with a minimalistic framework.
Flask additionally powers the backend server for Sprint. When builders create a Sprint utility, a Flask server is mechanically initiated. Nevertheless, on this article, we’ll discover deploying a customized Flask server. This strategy maximizes the flexibleness of Flask, extending past the usage of Sprint in our utility. It permits your complete internet utility to make the most of different frameworks along with Sprint and facilitates the development of authentication pipelines. Such options will not be included within the open-source model of Sprint with out this customization however can be found within the Enterprise model.
Native Improvement Conditions
There are just a few stipulations for organising the native growth setting. Whereas not all of them are strictly required, it’s extremely really helpful to comply with the rules offered beneath. It’s necessary to notice that this tutorial was created utilizing a Home windows 11 machine. Some modifications could also be essential for different working methods.
- Download Python. This tutorial makes use of Python 3.10.11. Its extremely really helpful so as to add Python to PATH throughout or after set up.
- Download Azure CLI. This shall be used to connect with Azure domestically by way of terminal.
- Download Docker.
- Download VS Code.
- VS Code Azure Extension.
- VS Code Azure Container Apps Extension.
- VS Code Docker Extension.
App Construction
Under is the define of the demo app’s construction, designed to host a number of purposes throughout the internet utility, all powered by a Flask server.
AZURE_DATA_ANALYTICS_WEBAPP/
|---|primary.py
|---|figures.py
|---|belongings/
|---|static/
|------|css/
|------|js/
|------|img/
|---|templates/
|------|dwelling.html
|---|necessities.txt
|---|Dockerfile
|---|.dockerignore
|---|.gitignore
|---|.env
|---|.venv
|---|README.md
Python Native Surroundings Setup
We’ll start by making a Python digital setting named .venv
within the VS Code terminal utilizing the instructions offered beneath. You should definitely embody .venv
in each the .gitignore
and .dockerignore
recordsdata, as these shouldn’t be uploaded or deployed.
python -m venv .venv
.venv/Scripts/activate
pip set up --upgrade pip
pip set up -r necessities.txt
The necessities for the challenge are listed within the necessities.txt
file as follows:
# necessities.txt# Internet App Framework Requiremed Recordsdata:
Flask==3.0.2
plotly==5.19.0
sprint==2.15.0
gunicorn==21.2.0
# Azure required recordsdata:
azure-identity==1.15.0
azure-keyvault-secrets==4.7.0
# Different Utilities:
python-dotenv==1.0.1
numpy==1.26.4
pandas==2.2.0
Flask Server
The principle entry level to the appliance shall be primary.py
, the place we are going to initialize and run the appliance. On this file, we are going to outline the Flask server, which is able to function the backend server for your complete utility.
At this stage, we don’t have any Sprint apps built-in; there’s only a single route outlined on the index web page of our utility that renders the dwelling.html
file. A route is a URL sample that handles and executes HTTP requests matching that sample. In our case, we’ve got a house route. Upon accessing the principle listing of the net utility (“/”), the dwelling.html
file shall be rendered.
# primary.pyfrom flask import Flask, render_template
# Initialize Flask server:
# Let Flask know the place the templates folder is situated
# by way of template_folder parameter
server = Flask(__name__, template_folder = "templates")
# Outline Routes:
@server.route("/")
def dwelling():
"""
Index URL to render dwelling.html
"""
return render_template("dwelling.html")
# Run the App:
if __name__ == "__main__":
server.run(host = "0.0.0.0", port = 5000, debug = True)
# Set debug to False throughout manufacturing
<!-- templates/dwelling.html file --><!DOCTYPE html>
<html>
<head>
<title>Azure Knowledge Analytics Internet Utility</title>
</head>
<physique>
<h1>Azure Container App Knowledge Analytics Utility
with Python Flask, Plotly Sprint & Docker
</h1>
</physique>
</html>
Observe that Flask expects HTML templates to be saved beneath the templates
folder. Flask makes use of Jinja to parametrize the HTML templates.
We at the moment are able to run our utility domestically for the primary time. Please notice that the debug mode is at the moment set to true, as proven above. Bear in mind to set this to false for manufacturing deployment. To run the app domestically, execute the command offered beneath after which go to http://localhost:5000/
in your browser.
python primary.py
We must always notice that when working domestically, as within the above instance, the appliance doesn’t use HTTPS. Nevertheless, Azure Container App considerably simplifies growth work by dealing with a lot of the heavy lifting associated to SSL/TLS termination.
It’s additionally necessary to say that the native execution of the appliance makes use of the default Flask HTTP server. For manufacturing deployment, nevertheless, we bind the appliance to a Gunicorn server whereas creating the Docker picture. Gunicorn, a Python WSGI HTTP server for Unix, is healthier suited to manufacturing environments. The set up of Gunicorn is included within the necessities.txt
file.
Sprint App
Now, we are going to modify the primary.py
file so as to add an occasion of a Sprint app. On this step, we initialize the Sprint app by offering the Flask server, specifying the bottom URL pathname for routing to the app, and indicating which belongings folder to make use of. The belongings folder can retailer pictures and customized fashion CSS recordsdata for the Sprint app.
# primary.pyfrom flask import Flask, render_template
from sprint import Sprint, html
# Initialize Flask server:
server = Flask(__name__, template_folder = "templates")
# Outline Routes:
@server.route("/")
def dwelling():
"""
Redirecting to dwelling web page.
"""
return render_template("dwelling.html")
# Sprint Apps:
app1 = Sprint(__name__, server = server,
url_base_pathname = "/sampleDashApp1/",
assets_folder = "belongings")
app1.format = html.Div([
html.H1("Sample Dash App"),
html.P("This is a simple Dash app running on a Flask server.")
])
# Run the App:
if __name__ == "__main__":
server.run(host = "0.0.0.0", port = 5000, debug = True)
# Set debug to False throughout manufacturing
Sprint helps most HTML tags, which could be specified instantly in Python, as illustrated within the instance above. To this point, we’ve added H1 header and P paragraph tags. Moreover, Sprint permits the addition of different parts, comparable to Sprint Core Elements. This characteristic permits us to include widgets in addition to plots from the Plotly library.
Including Plotly Figures
We’ll outline some pattern Plotly charts within the figures.py
file and subsequently incorporate them into the Sprint app.
# figures.pyimport plotly.categorical as px
import pandas as pd
import numpy as np
def line_chart():
"""
Pattern Plotly Line Chart
"""
df = pd.DataFrame({
"X": np.linspace(0, 10, 100),
"Y": np.sin(np.linspace(0, 10, 100))
})
fig = px.line(df, x = "X", y = "Y", title = "Line Chart")
return fig
def bar_chart():
"""
Pattern Plotly Bar Chart
"""
df = pd.DataFrame({
"Class": ["A", "B", "C", "D", "E"],
"Values": np.random.randint(10, 100, dimension = 5)
})
fig = px.bar(df, x = "Class", y = "Values", title = "Bar Chart")
return fig
If we modify the primary.py
file to import bar_chart
and line_chart
from the figures.py
file, we are able to then add these plots as graph parts to our Sprint app, as proven beneath.
# primary.py file# ...Remainder of the code
from figures import line_chart, bar_chart
# Sprint Apps:
app1 = Sprint(__name__, server = server,
url_base_pathname = "/sampleDashApp1/",
assets_folder = "belongings")
app1.format = html.Div([
html.H1("Sample Dash App"),
html.P("This is a simple Dash app running on a Flask server."),
html.H2("Sample Line Chart"),
dcc.Graph(figure=line_chart()),
html.H2("Sample Bar Chart"),
dcc.Graph(figure=bar_chart())
])
# ... Remainder of the code
Constructing and Working Docker Picture Domestically
We’ve now established a skeleton code for our utility and are able to construct our Docker picture. First, we have to allow virtualization from the motherboard’s BIOS settings, which is crucial for creating digital machines that Docker depends on. Secondly, the Docker software program and the VS Code Docker Extension must be put in.
As soon as the above steps are accomplished, we create a Dockerfile
in our primary listing and enter the next:
# Dockerfile# Set Python picture to make use of:
FROM python:3.11-slim-bullseye
# Retains Python from producing .pyc recordsdata within the container:
ENV PYTHONDONTWRITEBYTECODE=1
# Turns off buffering for simpler container logging:
ENV PYTHONUNBUFFERED=1
# Set up necessities:
RUN python -m pip set up --upgrade pip
COPY necessities.txt .
RUN python -m pip set up -r necessities.txt
# Set Working listing and duplicate recordsdata:
WORKDIR /app
COPY . /app
# Creates a non-root consumer with an express UID
# and provides permission to entry the /app folder:
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser
# Expose port 5000:
EXPOSE 5000
# Bind to make use of Gunicorn server
# and specify primary entry level primary.py/server object:
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "main:server"]
To construct the Docker picture, we execute the next command within the terminal:
docker construct --no-cache -t app:version1 .
With this step accomplished, we must always see a Docker picture created, seen within the VS Code Docker extension. On this occasion, we’ve got specified the title of the app as ‘app’ and the model of the picture as ‘version1’.
Now we’re able to run the app domestically. To create and begin a neighborhood Docker container, we execute the next command within the terminal:
docker run --env-file ./.env -p 5000:5000 app:version1
This may begin the Docker container domestically, permitting us to navigate to the app within the browser at http://localhost:5000/
. Within the Docker run command talked about above, we instruct Docker to make use of the .env
file situated in the principle listing because the environmental variables file. This file is the place we retailer app configuration variables and any secrets and techniques. It is essential to notice that the .env
file should be included in each .gitignore
and .dockerignore
recordsdata, as we are not looking for delicate data to be uploaded to Git or included within the Docker container. On Azure Container Apps, these parameters could be offered individually as environmental variables.
For our fundamental Azure deployment case, there isn’t a want to supply any environmental variables at this stage.
Under is the content material of the .dockerignore
file:
**/__pycache__**/.vscode
**/.venv
**/.env
**/.git
**/.gitignore
LICENSE
README.md
Now that we’ve got a working utility domestically and have efficiently created a Docker picture, we’re able to arrange Azure and deploy the Container App.
To proceed with the steps outlined beneath, it’s essential to have the Azure CLI (a terminal utility for speaking with Azure) put in, together with the VS Code Azure Container Apps extension.
Setup Azure Subscription
As soon as we’ve got created an Azure account, step one is to create a Subscription. A Subscription on Azure comprises a set of Azure assets linked to a billing account. For first-time Azure customers or college students, there are credit out there starting from $100 to $200. On this tutorial, nevertheless, we are going to concentrate on organising a paid account.
After signing up and logging into Azure, we navigate to ‘Subscriptions’, which shall be tied to our billing account. Right here, we have to present a reputation for the subscription and proceed with its creation.
Observe: Particular care needs to be taken to observe billing, particularly in the course of the studying interval. It’s advisable to set budgets and alerts to handle prices successfully.
Setup Azure Useful resource Group
Azure manages a set of cloud assets beneath what is named an Azure Useful resource Group. We’ll have to create certainly one of these teams to facilitate the creation of the required cloud assets.
From the principle Azure web page, we are able to navigate to ‘Useful resource Teams’ to create a brand new one.
This Useful resource Group shall be related to the Subscription we created within the earlier step. We might want to present a reputation for the Useful resource Group and choose a area. The area needs to be chosen based mostly on the closest geographical space to the place the appliance shall be primarily used.
Setup Azure Container Registry
Azure provides a container registry service generally known as Azure Container Registry, which permits us to host our Docker container pictures. This container registry serves as a repository for pictures, enabling model management over the container pictures. It additionally facilitates their deployment throughout varied cloud container providers, not restricted to Azure Container Apps alone. With this service, totally different variations of the app picture could be saved and deployed as wanted.
From the search bar within the Azure portal, we kind ‘Container Registries’ and click on the create button. This useful resource shall be hosted beneath the Useful resource Group we created within the earlier step. We must always select the identical area as earlier than and choose the Fundamental plan choice for the bottom value.
There’s one necessary setting that must be enabled on the Container Registry to permit us to deploy pictures to Azure Container App throughout the Azure portal. Go to the Properties of the Container Registry, allow the ‘Admin consumer’, after which save the adjustments.
Deploy Docker Picture to Azure Container Registry
Now that we’ve got our native Docker picture prepared and the Azure Container Registry setup full, we’re ready to add the container picture to Azure.
Within the VS Code terminal, we log in to Azure utilizing the Azure CLI (which should be put in):
az login
This motion will open a pop-up window in your browser, prompting you to sign up to Azure. As soon as accomplished, we at the moment are authenticated with Azure.
The subsequent step is to log in to the Container Registry utilizing the terminal and Azure CLI. This may be executed by executing the next command:
az acr login --name <azureContainerRegistryName>
As soon as we’ve got efficiently logged in to the Container Registry, our subsequent steps are to first tag the picture after which push it to the Azure Container App.
Observe that ‘app:version1’ represents the title and model of our app, which we assigned when creating the Docker picture within the earlier steps.
docker tag app:version1 <azureContainerRegistryName>.azurecr.io/app:version1
docker push <azureContainerRegistryName>.azurecr.io/app:version1
With this step accomplished, we must always be capable of view the picture beneath the ‘Repositories’ part of the Container Registry, as described above.
It’s necessary to notice that the above steps may even have been completed utilizing the VS Code Docker Extension, as a substitute for using the Azure CLI.
Setup Azure Container Apps Surroundings & Container App
The Azure Container Apps Surroundings is a useful resource that may handle a set of container apps. Whereas we can’t create a Container Apps Surroundings instantly, it may be arrange after we create an preliminary Container App.
To do that, we seek for ‘Container Apps’ within the Azure search bar and click on ‘Create’. Step one right here is to create a Container Apps Surroundings, as highlighted within the pink sq. field within the picture beneath.
We choose the consumption plan to pay just for what we use and for offering a simplified setup course of.
After creating the Container Apps Surroundings, we return to the setup web page for the Container App to proceed constructing the app. Throughout the Container setup web page, we choose Azure Container Registry and find the picture we’ve got beforehand uploaded.
For CPU and reminiscence, we go for the bottom quantity as it is a demo app. If there are any environmental variables specified within the .env
file for our native setting, we should enter them on this part. Alternatively, these environmental variables could be directed to Azure KeyVault.
We are able to skip the Bindings part for this tutorial and proceed to Ingress. On this part, we outline how Azure Container App handles site visitors. We allow Ingress and set site visitors to be accepted from anyplace if the appliance is to be accessible on the net. For inside purposes, the corporate’s VNet needs to be used.
Moreover, we set the port of the appliance to be 5000, which is identical because the Flask server’s port set throughout code growth.
After configuring all of those settings, we’re able to create our utility! Click on on ‘Assessment + create’.
As soon as the setup is full, navigate to the Container App web page to search out the URL of the appliance.
And that’s it! Our utility is now up and working on Azure!
Handle Revisions
Now that we’ve got deployed the primary model of our utility, we’ll cowl managing revisions.
As soon as we’ve got made adjustments to the code base and prepared with a revision, we run Docker deploy as earlier than with a brand new model title.
docker construct --no-cache -t app:version2 .
And add to Azure Container Registry:
az acr login --name <azureContainerRegistryName>
docker tag app:version2 <azureContainerRegistryName>.azurecr.io/app:version2
docker push <azureContainerRegistryName>.azurecr.io/app:version2
From right here on, we’ve got two choices. Both to make use of terminal and Azure CLI or go to Azure Container App web page and handle revisions from there. Right here we are going to cowl revision administration from Azure.
Hit “Create new revision” and supply a suffix to the brand new revision. Right here we’ll title it “version2”. Than click on on “app” check-box and choose edit.
In edit container part, choose the brand new model of the picture from Azure Container Registry and save. As soon as full, press create and new revision shall be created.
After we come again to Revisions, we see the brand new container revision is taking 100% of the site visitors. Though the outdated revision nonetheless stays and could be de-activated by way of Azure CLI.
We’ve efficiently deployed a Container App to Azure utilizing Python Flask & Sprint. Nevertheless, this utility is way from prepared for manufacturing launch.
For inside purposes, an authentication course of must be thought-about. Utilizing Azure Energetic Listing and the Python MSAL library, it’s doable to outline roles and entry lists for customers inside an organization’s listing and management the authentication circulate with a Flask server. The Sprint Enterprise model permits this integration in a a lot simpler manner. Nevertheless, the Enterprise model won’t be an choice for everybody. We should remind once more that the selection of utilizing a customized Flask server in our Sprint utility was made to beat the dearth of authentication assist within the open-source model. Including Microsoft Energetic Listing authentication pipeline shall be coated in a future article.
At this stage, the app is just utilizing some demo plots and artificial knowledge. With the app being deployed on Azure, we’ve got many choices to serve our knowledge to the app. The primary choice is to make the most of Azure Knowledge Lake Storage for a cheap file-based storage resolution. Whereas this selection offers storage at a really low value, it places the burden of computation on the net app. One other various is to make the most of Azure Databricks and its SQL Endpoint to dump heavy knowledge computations to a cloud cluster. These subjects shall be coated once more in one other tutorial.