Deploy a Python (Django or Flask) web app with PostgreSQL in Azure

In this tutorial, you'll deploy a data-driven Python web app (Django or Flask) with the Azure Database for PostgreSQL relational database service. The Python app is hosted in a fully managed Azure App Service which supports Python 3.7 or higher in a Linux server environment. You can start with a basic pricing tier that can be scaled up at any later time.

An architecture diagram showing an  App Service with a PostgreSQL database in Azure.

To complete this tutorial, you'll need:

1 - Sample application

Sample Python applications using the Flask and Django framework are provided to help you follow along with this tutorial. Download or clone one of the sample applications to your local workstation.

git clone https://github.com/Azure-Samples/msdocs-flask-postgresql-sample-app

To run the application locally, navigate into the application folder:

cd msdocs-flask-postgresql-sample-app

Create a virtual environment for the app:

py -m venv .venv
.venv/scripts/activate

Install the dependencies:

pip install -r requirements.txt

Note

If you are following along with this tutorial with your own app, look at the requirements.txt file description in each project's README.md file (Flask, Django) to see what packages you'll need.

This sample application requires an .env file describing how to connect to your local PostgreSQL instance. Create an .env file as shown below using the .env.sample file as a guide. Set the value of DBNAME to the name of an existing database in your local PostgreSQL instance. This tutorial assumes the database name is restaurant. Set the values of DBHOST, DBUSER, and DBPASS as appropriate for your local PostgreSQL instance.

DBNAME=<database name>
DBHOST=<database-hostname>
DBUSER=<db-user-name>
DBPASS=<db-password>

For Django, you can use SQLite locally instead of PostgreSQL by following the instructions in the comments of the settings.py file.

Create the restaurant and review database tables:

flask db init
flask db migrate -m "initial migration"

Run the app:

flask run

In a web browser, go to the sample application at http://127.0.0.1:5000 and add some restaurants and restaurant reviews to see how the app works.

A screenshot of the Flask web app with PostgreSQL running locally showing restaurants and restaurant reviews.

Tip

With Django, you can create users with the python manage.py createsuperuser command like you would with a typical Django app. For more information, see the documentation for django django-admin and manage.py. Use the superuser account to access the /admin portion of the web site. For Flask, use an extension such as Flask-admin to provide the same functionality.

Having issues? Let us know.

2 - Create a web app in Azure

To host your application in Azure, you need to create Azure App Service web app.

Sign in to the Azure portal and follow these steps to create your Azure App Service resource.

Instructions Screenshot
In the Azure portal:
  1. Enter app services in the search bar at the top of the Azure portal.

  2. Select the item labeled App Services under the under Services heading on the menu that appears below the search bar.

A screenshot showing how to use the search box in the top tool bar to find App Services in Azure portal.
On the App Services page, select + Create. A screenshot showing the location of the Create button on the App Services page in the Azure portal.
On the Create Web App page, fill out the form as follows:
  1. Resource Group → Select Create new and use a name of msdocs-python-postgres-webapp-rg.

  2. Name → Use msdocs-python-postgres-webapp-<unique-id>. The name must be unique across Azure with the web app's URL https://<app-service-name>.azurewebsites.com).

  3. Runtime stackPython 3.9

  4. Region → Any Azure region near you.

  5. App Service Plan → Select Create new under Linux Plan and use the name of msdocs-python-postgres-webapp-plan.

  6. App Service Plan → Select Change size under Sku and size to select a different App Service plan.

A screenshot showing how to fill out the form to create a new App Service in the Azure portal.
In the Spec Picker section, select an App Service plan. The App Service plan controls how many resources (CPU/memory) are available to your app and the cost of those resources.
  1. Select Dev/Test.

  2. Select B1 (Basic) Plan.

    The B1 Basic plan will incur a small charge against your Azure account but is recommended for better performance over the F1 (Free) plan.

  3. Select Apply.

A screenshot showing how to select the basic App Service plan in the Azure portal.
Back on the Create Web App page, select the Review + create button at the bottom of the screen.

This will take you to a page to review the configuration. Select Create to create your App Service.
A screenshot showing the location of the Review plus Create button in the Azure portal.

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

3 - Create the PostgreSQL database in Azure

You can create a PostgreSQL database in Azure using the Azure portal, Visual Studio Code, or the Azure CLI.

Sign in to the Azure portal and follow these steps to create your Azure Database for PostgreSQL resource.

Instructions Screenshot
In the Azure portal:
  1. Enter postgres in the search bar at the top of the Azure portal.

  2. Select the item labeled Azure Database for PostgreSQL flexible servers under the under Services heading on the menu that appears below the search bar.

A screenshot showing how to use the search box in the top tool bar to find Postgres Services in the Azure portal.
On the Azure Database for PostgreSQL flexible servers page, select + Create A screenshot showing the location of the Create button on the Azure Database for PostgreSQL servers page in the Azure portal.
On the next page, select Create under Flexible server. A screenshot showing the location of the Create Flexible Server button on the Azure Database for PostgreSQL deployment option page in the Azure portal.
On the Flexible server page, fill out the form as follows:
  1. Resource group → Select and use a name of msdocs-python-postgres-webapp-rg.

  2. Server name → Enter a name such as msdocs-python-postgres-webapp-db-<unique-id>. The name must be unique across Azure with the database server's URL https://<server-name>.postgres.database.azure.com). Allowed characters are A-Z, 0-9, and -.

  3. Region → Same Azure region used for the Web App.

  4. Data sourceNone

  5. Workload typeProduction

  6. Compute + storage → Select Configure server to select a different Compute + storage plan, which is discussed below.

  7. Availability zone → Keep the default (which is no preference).

  8. Version → Keep the default (which is the latest version).

A screenshot showing how to fill out the form to create a new Azure Database for PostgreSQL in the Azure portal.
On the Compute + storage page, continue configuring the flexible server:
  1. Compute tier → Select Burstable.

  2. Compute size → Select Standard_B1ms.

  3. Select Save to return to the main configuration page.

A screenshot showing how to select and configure the basic database service plan in the Azure portal.
Back on the main Flexible server page, finish the basic configuration:
  1. Administrator account → Enter a Admin username and Password to be used for the database administrator account.

  2. Select Next: Networking at the bottom of the screen.

Creating administrator account information for the PostgreSQL Flexible server in the Azure portal.
On the Networking page, add a firewall rule that allows your local environment to access the database server:
  1. Select Add current client IP address to allow access from your local environment.

  2. Select Review + Create at the bottom of the screen.

    This will take you to the Review page. Select Create to create your Azure Database for PostgreSQL Flexible Server Service.

A screenshot showing adding current IP as a firewall rule for the PostgreSQL Flexible server in the Azure portal.

In your local environment using the PostgreSQL interactive terminal psql, connect to the PostgreSQL database server, and create the restaurant database:

psql --host=<server-name>.postgres.database.azure.com \
     --port=5432 \
     --username=<admin-user> \
     --dbname=postgres

postgres=> CREATE DATABASE restaurant;

The values of <server-name> and <admin-user> are the values from a previous step. If you have trouble connecting, restart the database and try again.

Optionally, verify that the restaurant database was successfully created by running \c restaurant to change the prompt from postgres (default) to the restaurant. Type \? to show help or \q to quit.

Having issues? Let us know.

4 - Allow web app to access the database

After the Azure Database for PostgreSQL server is created, configure access to the server from the web app by adding a firewall rule. This can be done through the Azure portal or the Azure CLI.

If you're working in VS Code, right-click the database server and select Open in Portal to go to the Azure portal. Or, go to the Azure Cloud Shell and run the Azure CLI commands.

Instructions Screenshot
Add a rule to allow your web app to access the PostgreSQL Flexible server.
  1. In the left resource page for the server, select Networking.

  2. Select the checkbox next to Allow public access from any Azure service within Azure to this server.

  3. Select Save to save the change.

To further secure communication between production web apps and database servers, you should use an Azure Virtual Network.
A screenshot showing how to add access from other Azure services to a PostgreSQL database in the Azure portal.

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

5 - Connect the web app to the database

With the web app and PostgreSQL database created, the next step is to connect the web app to the PostgreSQL database in Azure.

The web app code uses database information in four environment variables named DBHOST, DBNAME, DBUSER, and DBPASS to connect to the PostgresSQL server.

Instructions Screenshot
In the portal, go to the App Service page for the web app.
  1. Select Configuration under Settings on the left side.

  2. Select Application settings at the top of the page.

A screenshot showing how to navigate to App Settings in the Azure portal.
Create application settings:
  1. Select + New application setting to create settings for each of the following values (which are expected by the django sample app):

    • DBHOST → Use the server name you used earlier when created the database, for example, msdocs-python-postgres-webapp-db-<unique id>. The code in azuresite/production.py automatically appends .postgres.database.azure.com to create the full PostgreSQL server URL.
    • DBNAME → Enter restaurant, the name of the application database.
    • DBUSER → The administrator user name used when you provisioned the database.
    • DBPASS → The administrator secure password you created earlier.
  2. Confirm you have four settings and view their hidden values.

  3. Select Save and to apply the settings.

A screenshot showing how to configure the App Settings in the Azure portal.

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

6 - Deploy your application code to Azure

Azure App service supports multiple methods to deploy your application code to Azure including support for GitHub Actions and all major CI/CD tools. This article focuses on how to deploy your code from your local workstation to Azure.

To deploy a web app from VS Code, you must have the Azure Tools extension pack installed and be signed into Azure from VS Code.

Instructions Screenshot
Locate the Azure icon in the left-hand toolbar and select it to bring up the Azure Tools for VS Code extension. A screenshot showing how to locate the Azure Tools extension in VS Code.
In the Azure Tools extension:
  1. Expand RESOURCES. (Make sure resources are sorted by resource type.)

  2. Right-click your web app to bring up the context menu.

  3. Select Deploy to Web App... from the menu.

A screenshot showing how to deploy a web app in VS Code.
Select your web app as the web app to deploy in the dialog at the top of the screen.

Select Deploy in the dialog box.
A screenshot showing how to deploy a web app in VS Code: selecting the code to deploy. A screenshot showing how to deploy a web app in VS Code: a dialog box to confirm deployment.
Select Yes to update your build configuration and improve deployment performance. A screenshot showing how to deploy a web app in VS Code: a dialog box to choose to always deploy to the app service.
When the deployment is complete, a dialog box will appear in the lower right corner of the screen with an option to browse to the website. If you use this link, the web page will report an error because the web app isn't ready until you do the migration in the next step. You may see another dialog box warning of this problem. A screenshot showing how to deploy a web app in VS Code: a dialog box with choice to browse to website. A screenshot showing how to deploy a web app in VS Code: a dialog box with choice to view deployment details.

Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.

7 - Migrate app database

With the code deployed and the database in place, the app is almost ready to use. First, you need to establish the necessary schema in the database itself. You do this by "migrating" the data models in the Django app to the database.

Step 1. Create SSH session and connect to web app server.

Navigate to page for the App Service instance in the Azure portal.

  1. Select SSH, under Development Tools on the left side
  2. Then Go to open an SSH console on the web app server. (It may take a minute to connect for the first time as the web app container needs to start.)

Note

If you cannot connect to the SSH session, then the app itself has failed to start. Check the diagnostic logs for details. For example, if you haven't created the necessary app settings in the previous section, the logs will indicate KeyError: 'DBNAME'.

Step 2. In the SSH session, run the following command to migrate the models into the database schema (you can paste commands using Ctrl+Shift+V):

When you deploy the Flask sample app to Azure App Service, the database tables are created automatically in Azure PostgreSQL. If the tables aren't created, try the following command:

# Create database tables
flask db init

If you encounter any errors related to connecting to the database, check the values of the application settings of the App Service created in the previous section, namely DBHOST, DBNAME, DBUSER, and DBPASS. Without those settings, the migrate command can't communicate with the database.

Tip

In an SSH session, for Django you can also create users with the python manage.py createsuperuser command like you would with a typical Django app. For more information, see the documentation for django django-admin and manage.py. Use the superuser account to access the /admin portion of the web site. For Flask, use an extension such as Flask-admin to provide the same functionality.

Having issues? Let us know.

8 - Browse to the app

Browse to the deployed application in your web browser at the URL http://<app-name>.azurewebsites.net. It can take a minute or two for the app to start, so if you see a default app page, wait a minute and refresh the browser.

When you see your sample web app, it's running in a Linux container in App Service using a built-in image Congratulations! You've deployed your Python app to App Service.

Having issues? Let us know.

9 - Stream diagnostic logs

Azure App Service captures all messages output to the console to help you diagnose issues with your application. The sample app includes print() statements to demonstrate this capability as shown below.

def index(request):
    print('Request for index page received')

    restaurants = Restaurant.objects.annotate(avg_rating=Avg('review__rating')).annotate(review_count=Count('review'))
    return render(request, 'restaurant_review/index.html', {'restaurants': restaurants })

You can access the console logs generated from inside the container that hosts the app on Azure.

Instructions Screenshot
First, you need to enable streaming logs in Azure App Service. Navigate to page for the App Service instance in the Azure portal.
  1. Select the App Service logs under the Monitoring heading in the menu on the left side of the page.

  2. Change the Application Logging property from Off to File System.

  3. Enter a retention period of 30 days for the logs.

  4. Select Save to save your changes.

A screenshot showing how to set application logging in the Azure portal.
Select the Log stream item from the menu under the Monitoring section. Refresh the home page in the app or attempt other requests to generate some log messages.

You will see any log messages generated by your app and messages generated by the service in the output.
A screenshot showing how to stream logs in the Azure portal.

Having issues? Let us know.

Clean up resources

You can leave the app and database running as long as you want for further development work and skip ahead to Next steps.

However, when you're finished with the sample app, you can remove all of the resources for the app from Azure to ensure you don't incur other charges and keep your Azure subscription uncluttered. Removing the resource group also removes all resources in the resource group and is the fastest way to remove all Azure resources for your app.

Follow these steps while signed-in to the Azure portal to delete a resource group.

Instructions Screenshot
Navigate to the resource group in the Azure portal.
  1. Enter the name of the resource group in the search bar at the top of the page.
  2. Under the Resource Groups heading, select the name of the resource group to navigate to it.
A screenshot showing how to find resource group in the Azure portal.
Select the Delete resource group button at the top of the page. A screenshot showing how to delete a resource group in the Azure portal.
In the confirmation dialog, enter the name of the resource group to confirm deletion. Select Delete to delete the resource group.

Having issues? Let us know.

Next steps

Learn how to map a custom DNS name to your app:

Learn how App Service runs a Python app: