Tutorial: Deploy an ASP.NET Core and Azure SQL Database app to Azure App Service
Članak
17 min. za čitanje
In this tutorial, you'll learn how to deploy an ASP.NET Core app to Azure App Service and connect to an Azure SQL Database. Azure App Service is a highly scalable, self-patching, web-hosting service that can easily deploy apps on Windows or Linux. Although this tutorial uses an ASP.NET Core 6.0 app, the process is the same for other versions of ASP.NET Core and ASP.NET Framework.
This article assumes you're familiar with .NET and have it installed locally. You'll also need an Azure account with an active subscription. If you don't have an Azure account, you can create one for free.
git clone https://github.com/Azure-Samples/msdocs-app-service-sqldb-dotnetcore.git
cd msdocs-app-service-sqldb-dotnetcore
2 - Create the App Service
Let's first create the Azure App Service that hosts our deployed Web App. There are several different ways to create an App Service depending on your ideal workflow.
Sign in to the Azure portal and follow these steps to create your Azure App Service resources:
Instructions
Screenshot
In the Azure portal:
Enter App Service in the search bar at the top of the Azure portal and select the App Services item that appears in the results.
On the App Services page, select + Create
On the Create Web App page, fill out the form as follows.
Resource Group → Select Create new and enter a name of msdocs-core-sql.
Name → Enter a unique name of your choice, such as coreSqlXYZ, where XYZ are letters or numbers of your choosing. This App Service name must be unique across Azure.
Publish → Code
Runtime stack → .NET 6.0
Operating System → Windows
Region → Any Azure region near you.
App Service Plan → Select Create New and give your App Service plan a name of MyAppServicePlan.
Select Change size under Sku and size settings to select the App Service plan specifications.
The App Service plan controls what resources (CPU/memory) are available to your app and the cost of those resources. You can learn more about choosing an App Service plan in the article App Service plan overview.
For this example, select Dev / Test at the top of the screen and select the F1 (Free) plan.
When finished, select Apply to apply your changes.
On the main Create Web App page, select the Review + create button at the bottom of the screen.
On the Review page, select Create to create your App Service. The deployment of this new App Service may take a few minutes to complete.
First, create a resource group using the az group create command. The resource group acts as a container for all of the Azure resources related to this application.
# Use 'az account list-locations --output table' to list available locations close to you
# Create a resource group
az group create --location eastus --name msdocs-core-sql
The --sku parameter defines the size (CPU, memory) and cost of the app service plan. This example uses the F1 (Free) service plan. For a full list of App Service plans, view the App Service pricing page.
# Change 123 to any three characters to form a unique name
az appservice plan create \
--name msdocs-core-sql-plan-123 \
--resource-group msdocs-core-sql \
--sku F1
Finally, create the App Service web app using the az webapp create command.
The App Service name is used as both the name of the resource in Azure and to form the fully qualified domain name for your app in the form of https://<app service name>.azurewebsites.com.
The runtime specifies what version of .NET your app is running. This example uses .NET 6.0 LTS. To list all available runtimes, use the command az webapp list-runtimes --os linux --output table for Linux and az webapp list-runtimes --os windows --output table for Windows.
Sign in to the Azure portal and follow these steps to create your Azure App Service resources:
Instructions
Screenshot
In the Azure portal:
In the search bar at the top of the Azure portal, enter SQL. Select the item labeled SQL Servers from the search results.
On the SQL Servers page, select + Create.
On the Create Server page, fill out the form as follows.
Resource Group - choose the msdocs-core-sql group you created.
Server name - enter a globally unique name such as coredbserverXYZ where XYZ are random numbers.
Location - select a region near you.
Authentication method - select Use SQL Authentication.
Server admin login - enter a username of your choice.
Password - enter a password you'll remember.
After your SQL Server has been provisioned, in the search bar at the top of the Azure portal, enter SQL. Select the item labeled SQL Databases from the search results.
On the SQL Databases page, select + Create.
On the Create Database page, fill out the form as follows.
Resource Group - choose the msdocs-core-sql group you created earlier.
Database name - enter a value of coreDb.
Server - select the coredbserverXYZ you created earlier.
Leave the rest of the settings at their default, and then select Review + create.
Select the Create button once Azure validates your settings. Provisioning the database may take a few minutes.
First, create an Azure SQL Server to host the database. A new Azure SQL Server is created by using the az sql server create command.
Replace the server-name placeholder with a unique SQL Database name. The SQL Database name is used as part of the globally unique SQL Database endpoint. Also, replace db-username and db-username with a username and password of your choice.
az sql server create \
--location eastus \
--resource-group msdocs-core-sql \
--name <server-name> \
--admin-user <db-username> \
--admin-password <db-password>
Setting up an SQL Server might take a few minutes. When the resource is available, we can create a database with the az sql db create command.
az sql db create \
--resource-group msdocs-core-sql \
--server <server-name> \
--name coreDb
4 - Connect the App to the Database
Next, we must connect the App hosted in our App Service to our database using a Connection String. You can use Service Connector to create the connection.
Sign in to the Azure portal and follow the steps to create your Azure App Service resources:
Instructions
Screenshot
In the Azure portal:
Type the name of your app in the search box at the top of the screen.
In the search results, select the app to navigate to it.
On the left navigation, select Service Connector.
Select Create.
On the Create connection page
select or enter the following settings:
Service Type: Select SQL Database.
SQL server: Enter your SQL Database server name.
SQL database: Select coreDB.
Select Next: Authentication.
Under the Authentication tab:
Specify the username and password of your SQL database.
Select Next: Networking, then select Next: Review + Create.
After validation is complete, select Create to create the service connection.It might take 1 minute to complete the operation. Click Refresh button to see the SQL database connection.
In the Service Connector page:
Expand the connection by selecting > next to it. AZURE_SQL_CONNECTIONSTRING is the connection string generated for you.
Select Hidden value. Click to show value and copy the connection string for later.
Your app can now connect to the SQL database. Next, let's generate the schema for our data using Entity Framework Core.
When prompted, provide the administrator username and password for the SQL database.
Note
The CLI command does everything the app needs to successfully connect to the database, including:
In your App Service app, detects the platform as .NET and adds a connection string with the name AZURE_SQL_CONNECTIONSTRING, which your code can use for its database connection. If the connection string is already in use, AZURE_SQL_<connection-name>_CONNECTIONSTRING is used for the name instead.
In your SQL database server, allows Azure services to access the SQL database server.
Copy this connection string value from the output for later.
To see the entirety of the command output, drop the --query in the command.
5 - Generate the Database Schema
To generate our database schema, set up a firewall rule on the SQL database server. This rule lets your local computer connect to Azure. For this step, you'll need to know your local computer's IP address. For more information about how to find the IP address, see here.
az sql server firewall-rule create --resource-group msdocs-core-sql --server <yoursqlserver> --name LocalAccess --start-ip-address <your-ip> --end-ip-address <your-ip>
Next, update the appsettings.json file in the sample project with the connection string Azure SQL Database. The update allows us to run migrations locally against our database hosted in Azure. Replace the username and password placeholders with the values you chose when creating your database.
From a local terminal, run the following commands to install the necessary CLI tools for Entity Framework Core, create an initial database migration file, and apply those changes to update the database:
cd <sample-root>\DotNetCoreSqlDb
dotnet tool install -g dotnet-ef
dotnet ef migrations add InitialCreate
dotnet ef database update
After the migration finishes, the correct schema is created.
If you receive the error Client with IP address xxx.xxx.xxx.xxx is not allowed to access the server, that means the IP address you entered into your Azure firewall rule is incorrect. To fix this issue, update the Azure firewall rule with the IP address provided in the error message.
6 - Deploy to the App Service
That we're able to create the schema in the database means that our .NET app can connect to the Azure database successfully with the new connection string. Remember that the service connector already configured the AZURE_SQL_CONNECTIONSTRING connection string in our App Service app. We're now ready to deploy our .NET app to the App Service.
In the Visual Studio solution explorer, right-click on the DotNetCoreSqlDb project node and select publish. A publishing workflow dialog will open. Select Azure as the deployment target and select next.
Select Azure App Service (Windows) as the host of your app and then select Next.
If you're not already logged into an Azure account, you'll be prompted to do so. Select Sign In to launch the Azure sign-in page and then enter your account credentials. You can also select Create an Account to set up a new account if you don't have one already.
On the App Service step, make sure your Subscription is selected, and then locate the App Service you created under the App Service instances selection box. Select that App Service and then select finish.
On the publishing profile summary view, select Publish to deploy your app to Azure. This process may take a few moments, but once it completes your app will be successfully published to Azure.
Instructions
Screenshot
In your VS Code environment, verify that the Azure Account and Azure App Service extensions are installed. Ensure you're logged into your Azure Account using the Account extension.
If you're not already logged in through the Azure Account extension, you use Ctrl + Shift + P to open the VS Code Command Palette. From there you can type Azure: Sign In and then hit enter to launch a browser window to sign in.
In the Visual Studio Code terminal, run the .NET CLI command below. This command generates a deployable publish folder for the app in the bin/release/publish directory.
dotnet publish -c Release
Right-click on the generated publish folder in the Visual Studio Code explorer and select Deploy to Web App.
A new workflow will open in the command palette at the top of the screen. Select the subscription you would like to publish your app to.
Select the App Service web app you created earlier.
If Visual Studio Code prompts you to confirm, click deploy. The deployment process may take a few moments. When the process completes, a notification should appear in the bottom right corner prompting you to browse to the deployed app.
You can deploy your application code from a local Git repository to Azure by configuring a Git remote in your local repo pointing at your Azure App Service. The URL of the remote repository and Git credentials needed for configuration can be retrieved using either the Azure portal or the Azure CLI.
Enter the name of your App Service in the search box at the top of the screen.
In the search results, select the App Service to navigate to it.
On the page for the App Service:
Select Deployment Center from the menu on the left side of the screen.
In the dropdown list labeled Source, select Local Git.
Select Save from the top menu bar.
After saving, on the Deployment Center page:
Navigate to the Local Git/FTPS credentials tab.
Locate the Git Clone URI, Username and Password fields under the Application Scope credentials.
Keep this screen open or copy these credentials to use momentarily when you deploy your code to the remote repository. You will only need the part of the username starting with $ onward for authenticating via the Git prompt.
When you push code to the remote Git repository for the first time, these credentials are needed to authenticate.
Next, configure the deployment source for your web app to be local Git using the az webapp deployment source command.
Retrieve the deployment credentials for your application. These will be needed for Git to authenticate to Azure when you push code to Azure in a later step.
Next, let's add an Azure origin to our local Git repo using the App Service Git deployment URL from the step where we created our App Service. Make sure to replace your app name in the url below. You can also get this completed URL from the Azure Portal Local Git/FTPS Credentials tab.
Finally, push your code using the correct origin and branch name.
## Master is the default deployment branch for App Service - this will ensure our local main branch works for the deployment
git push azure main:master
Enter your password if you are prompted to do so. This command will take a moment to run as it deploys your app code to the Azure App Service.
7 - Browse the Deployed Application and File Directory
Go back to your web app in the browser. You can always get back to your site by selecting the Browse link at the top of the App Service overview page. If you refresh the page, you can now create todos and see them displayed on the home page. Congratulations!
Next, let's take a closer look at the deployed files of our app using a tool called Kudu.
Azure App Service provides a web-based diagnostics console named Kudu. Kudu lets you examine the server-hosting environment, view deployed files to Azure, review deployment history, and even open an SSH session into the hosting environment.
To use Kudu, go to one of the following URLs. You'll need to sign into the Kudu site with your Azure credentials.
For apps deployed in Free, Shared, Basic, Standard, and Premium App Service plans - https://<app-name>.scm.azurewebsites.net
For apps deployed in Isolated service plans - https://<app-name>.scm.<ase-name>.p.azurewebsites.net
From the main page in Kudu, you can find information about the application-hosting environment, app settings, deployments, and browse the files in the wwwroot directory.
8 - Configure and Stream Application Logs
Azure App Service captures messages logged to the console to assist you in diagnosing issues with your application. The sample app outputs console log messages in each of its endpoints to demonstrate this capability. The contents of the App Service diagnostic logs can be reviewed in the Azure portal, Visual Studio Code, or using the Azure CLI.
First, you need to enabled streaming logs in Azure App Service. Navigate to the page for the App Service instance in the Azure portal.
Select the App Service logs under the Monitoring heading in the menu on the left side of the page.
Change the Application Logging (File System) property to On.
Enter a retention period of 30 days for the logs.
Select Save to save your changes.
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.
Instructions
Screenshot
In the App Service section of the Azure Tools for VS Code extension, right-click on your App Service instance and select Start Streaming Logs from the menu.
The console logs appear in VS Code's Output window. 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 as well as other messages generated by the service in the output.
You can configure Azure App Service to output logs to the App Service filesystem using the az webapp log config command.
You can also stream logs directly to the console using the az webapp log tail command.
az webapp log tail \
--name $APP_SERVICE_NAME \
--resource-group $RESOURCE_GROUP_NAME
Refresh the home page in the app or attempt other requests to generate some log messages. The output should look similar to the below output.
2022-01-06T22:37:11 Welcome, you are now connected to log-streaming service. The default timeout is 2 hours. Change the timeout with the App Setting SCM_LOGSTREAM_TIMEOUT (in seconds).
2022-01-06 22:37:16.195 +00:00 [Information] Microsoft.AspNetCore.Hosting.Diagnostics: Request starting HTTP/1.1 GET https://coresql456.azurewebsites.net/ - -
2022-01-06 22:37:16.195 +00:00 [Trace] Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware: All hosts are allowed.
2022-01-06 22:37:16.195 +00:00 [Debug] Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: The request path / does not match a supported file type
2022-01-06 22:37:16.195 +00:00 [Debug] Microsoft.AspNetCore.Routing.Matching.DfaMatcher: 1 candidate(s) found for the request path '/'
2022-01-06 22:37:16.195 +00:00 [Debug] Microsoft.AspNetCore.Routing.Matching.DfaMatcher: Endpoint 'DotNetCoresql-db.Controllers.TodosController.Index (DotNetCoresql-db)' with route pattern '{controller=Todos}/{action=Index}/{id?}' is valid for the request path '/'
Clean up resources
When you're finished, you can delete all of the resources from Azure by deleting the resource group for the application. It deletes all of the resources contained inside the group.
Follow these steps while signed-in to the Azure portal to delete a resource group:
Instructions
Screenshot
In the Azure portal, enter the name of the resource group in the search bar.
Select the name of the resource group in the search results to navigate to it.
Select the Delete resource group button at the top of the page.
In the confirmation dialog, enter the name of the resource group to confirm deletion. Select the Delete button at the bottom of the page to delete the resource group.
Instructions
Screenshot
In the Azure Tools extension for VS Code:
Locate the section named Resource Groups and right-click on the name of the resource group you want to delete.
Select Delete from the menu.
Enter the name of the resource group in the dialog box to confirm deletion of the resource group.
You can delete the resource group you created by using the az group delete command. Deleting the resource group deletes all of the resources contained within it.
az group delete --name msdocs-core-sql
Next steps
Advance to the next tutorial to learn how to map a custom DNS name to your app.