37,19 €
Microsoft Azure is currently one of the fastest growing public cloud service providers thanks to its sophisticated set of services for building fault-tolerant and scalable cloud-based applications.
This second edition of Azure for Developers will take you on a journey through the various PaaS services available in Azure, including Azure App Service, Azure Functions, and Azure SQL Databases, showing you how to build a complete and reliable system with ease. Throughout the book, you’ll discover ways to enhance your skills when building cloud-based solutions leveraging different SQL/NoSQL databases, serverless and messaging components, containerized solutions, and even search engines such as Azure Cognitive Search. That’s not all!! The book also covers more advanced scenarios such as scalability best practices, serving static content with Azure CDN, and distributing loads with Azure Traffic Manager, Azure Application Gateway, and Azure Front Door.
By the end of this Azure book, you’ll be able to build modern applications on the Azure cloud using the most popular and promising technologies to make your solutions reliable, stable, and efficient.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 591
Veröffentlichungsjahr: 2022
Implement rich Azure PaaS ecosystems using containers, serverless services, and storage solutions
Kamil Mrzygłód
BIRMINGHAM—MUMBAI
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rahul Nair
Publishing Product Manager: Meeta Rajani
Senior Content Development Editor: Sayali Pingale
Technical Editor: Arjun Varma
Copy Editor: Safis Editing
Book Project Manager: Aishwarya Mohan
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Sinhayna Bais
Marketing Co-ordinator: Nimisha Dua
Senior Marketing Co-ordinator: Sanjana Gupta
First published: November 2018
Second edition: August 2022
Production reference: 1260822
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
978-1-80324-009-1
www.packt.com
To Klaudia – for putting confidence in me.
Kamil Mrzygłód is a skilled software developer, architect, and Microsoft Azure MVP. He is focused on delivering fast, reliable, and flexible cloud solutions based on the Microsoft Azure platform. He has spoken at multiple conferences and meetups, working on open source software (OSS) projects and driving workshops for different people and companies. In recent years, he has developed an interest in Azure serverless architectures, data analysis, and big data components. Currently, he works as an independent cloud consultant for various clients. His current goal is to make the world of cloud computing as accessible as it can be so that it’s possible to lower the learning curve of this technology and help others start using it.
“I would like to take an opportunity and thank the whole team working on the new edition of this book for their professionalism and constant feedback. You made the book as good as it is now.”
Jay Freeman has worked in the IT industry for over 25 years and has been helping organizations to transform the way they work by adding value and helping to deliver on time development practices, software and cloud architecture, and agile practices.
He has worked for some of the largest organizations in retail, finance, Formula One, automotive, education, transport, and specialist security firms, which gives him a great breadth of knowledge across many areas.
These days, Jay focuses mainly on helping organizations either migrate their on-premises infrastructure and data to the cloud or with the architecting and designing of existing cloud deployments to achieve maximum security and performance, while keeping costs to a minimum.
“I have been extremely fortunate over many years to have been able to work with some of the most experienced people and largest companies, which has helped me progress. I have spent many late nights learning new technologies, which I have always had a real passion for, from the age of 11 when I wrote my first program on a Commodore C64. Families of IT professionals don’t always get as much time with us as they would like, so I want to thank my wife for really supporting me on my late nights and early mornings and both my boys for understanding that daddy can’t always play.”
Microsoft Azure is one of the most popular cloud computing platforms that are available publicly. As more and more companies decide to migrate their on-premises workloads and modernize them, expertise in at least one cloud vendor becomes critical when planning your next career steps.
The goal of this book is to help you to understand how Microsoft Azure works and what can be achieved when choosing cloud products over a traditional model of hosting. It focuses on presenting managed services such as Azure App Service, Azure SQL Database, and Azure Container Registry, addressing the current direction of modern architectures and the plans of many companies.
This book is targeted at developers who are familiar with concepts of programming, architecture, and deployment to a desired hosting environment. As Microsoft Azure is a technology closely related to the .NET platform, prior knowledge of that technology stack will help you get the most out of this book.
However, as the cloud is a technology-agnostic platform, there are also examples addressing other programming languages that are supported.
Chapter 1, Web Applications in Azure – Azure App Service, shows you how to build and host web apps in Azure.
Chapter 2, Using Azure Container Registry for Storing and Managing Images, discusses building and hosting Docker images with application code and dependencies.
Chapter 3, Deploying Web Applications as Containers, examines using Docker images as artifacts and running them using Azure services.
Chapter 4, Using Azure Container Instances for Ad Hoc Application Hosting, covers running containers in Azure without provisioning additional infrastructure.
Chapter 5, Building a Search Engine with Azure Cognitive Search, delves into using Azure Search as a managed search engine.
Chapter 6, Mobile Notifications with Notification Hub, discusses enriching applications with notifications.
Chapter 7, Serverless and Azure Functions, shows you how to build serverless applications with a function-as-a-service approach.
Chapter 8, Durable Functions, examines enhancing serverless architecture with a controlled model of data processing.
Chapter 9, Integrating Different Components with Logic Apps, delves into using Azure Logic Apps as a managed service for building low-code solutions.
Chapter 10, Swiss Army Knife – Azure CosmosDB, provides an introduction to Azure Cosmos DB.
Chapter 11, Reactive Architecture with Event Grid, examines using Azure Event Grid with topics and subscriptions.
Chapter 12, Using Azure Storage – Tables, Queues, Files, and Blobs, discusses leveraging the Azure Storage service as a flexible solution for storing data.
Chapter 13, Big Data Pipeline – Azure Event Hubs, explores implementing a streaming solution for events.
Chapter 14, Real-Time Data Analysis – Azure Stream Analytics, covers the analysis of data streams with the in-built functionalities of Azure Stream Analytics.
Chapter 15, Enterprise Integration – Azure Service Bus, focuses on advanced messaging scenarios based on Azure Service Bus.
Chapter 16, Using Application Insights to Monitor Your Applications, delves into a managed monitoring solution based on Azure Application Insights.
Chapter 17, SQL in Azure – Azure SQL, covers hosting SQL Server in Azure.
Chapter 18, Big Data Storage – Azure Data Lake, examines building a data lake in Azure.
Chapter 19, Scaling Azure Applications, discusses how to scale Azure services depending on the requirements and available features.
Chapter 20, Serving Static Content Using Azure CDN, delves into using Azure CDN for integration with applications and improving performance.
Chapter 21, Managing APIs with Azure API Management, focuses on managing APIs and their schemas.
Chapter 22, Building a Scalable Entry Point for Your Service with Azure Front Door, covers load balancing using a global Azure service.
Chapter 23, Azure Application Gateway as a Web Traffic Load Balancer, delves into controlling traffic in your system using a managed load balancer.
Chapter 24, Distributing Load with Azure Traffic Manager, explores implementing DNS-based load balancing.
Chapter 25, Tips and Tricks in Azure, examines various tricks to improve your Azure skills.
Depending on the technology stack you’re using, the required software will be different. As most of the examples are presented using .NET 6, basic knowledge of that technology will help you to quickly understand the details of the described topics. There are also multiple samples presented in other technologies such as Java or JavaScript to give you a better perspective of the differences between available runtimes.
All the exercises and examples assume that you’re able to install VS Code as an IDE. You may work with other IDEs as well, although the book won’t address them directly.
Some exercises describe a development process with Visual Studio. It’s perfectly fine to use the free Community edition if you don’t have access to the commercial license.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Azure-for-Developers-Second-Edition. If there’s an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/IPgBV.
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “If your input contains a property named Date, you can use SELECT date to push it to your output.”
A block of code is set as follows:
SELECT COUNT(DISTINCT Column1) AS Count_column1, System.TIMESTAMP() AS Time FROM Input TIMESTAMP BY TIME GROUP BY TumblingWindow(second, 2)Code output or a command-line entry is set as follows:
npm install applicationinsights
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “When you click the Review + create button and confirm creation, an alert rule will be created.”
Tips or Important Notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve read Azure for Developers, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
The objective of Part 1 is to present the most common Azure services. Components such as Azure App Service, WebJobs, and Azure Search are widely used and offer a great number of different features, starting from different deployment options, runtimes, and even slots for multiple application versions. With different containers also available, the whole journey can start to get complicated – we’re here to help you understand PaaS and the flexibility it offers.
This part of the book comprises the following chapters:
Chapter 1, Web Applications in Azure – Azure App ServiceChapter 2, Using Azure Container Registry for Storing and Managing ImagesChapter 3, Deploying Web Applications as ContainersChapter 4, Using Azure Container Instances for Ad Hoc Application HostingChapter 5, Building a Search Engine with Azure Cognitive SearchChapter 6, Mobile Notifications with Notification HubsAzure App Service is one of the biggest and most used services available in the Azure cloud. It allows the easy development of web applications with multiple features available (such as support for different platforms, including .NET, PHP: Hypertext Preprocessor (PHP), and Java), manual and automated scaling, and different performance options. It's a general platform and runtime that fuels other services, such as WebJobs and Azure Functions. This chapter is designed to get you familiar with the basics of web development in Microsoft Azure.
In this chapter, you will learn about the following topics:
Creating and deploying an Azure App Service resourceWorking with different operating systems and platformsChoosing the right App Service plan and exploring what its features areSecuring App Service resources using different security providersConfiguring networking for Azure App ServiceTo perform the exercises in this chapter, you will need the following:
Access to an Azure subscription.Visual Studio 2022 with the Azure development workload installed. All editions would suffice (Community/Professional/Enterprise).Visual Studio Code (VS Code) installed (available at https://code.visualstudio.com/).The Azure command-line interface (Azure CLI) (https://docs.microsoft.com/en-us/cli/azure/).To get started with Azure App Service, you must learn how to create that service and deploy your code. Throughout the chapter, you will see how many ways Azure provides for doing so. Depending on your current needs and the specification of your application, each path can be easier or harder; still, the strength of a cloud and Platform-as-a-Service (PaaS) offering lies in the straightforward and intuitive process of provisioning new components of your system.
Note
PaaS is one of the several cloud infrastructure models available. In general, it stands between Infrastructure-as-a-Service (IaaS) and Software-as-a-Service (SaaS), offering a balance between the ability to manage underlying infrastructure and abstraction over used components.
Let's now check the different ways to deploy your very first Azure App Service resource.
To begin, you will deploy your service using the Azure portal. All you will need is a browser with access to the internet. Enter https://portal.azure.com to get started.
To create an Azure App Service resource in the Azure portal, you must first find the option to do so in the list of available services. The easiest way to do so is to click on the + Create a resource button and then click on Web App, as shown in the following screenshot:
Figure 1.1 – Create a resource screen
Alternatively, you can utilize the search box at the top of the screen to quickly access any service, as shown in the following screenshot:
Figure 1.2 – Searching for a resource via the search box
As you can see, the Azure portal already displays the most popular services. If for some reason the Web App/App Service resource is not displayed, use the search box by entering the name of a service you are looking for.
When you click on the Web App item, you will see the first step of a resource creator, which will guide you through the process of provisioning your application. Now, we will go through all the steps and describe in detail the different parameters that are available to you.
Tip
Here, we are using the raw version of Azure App Service, which comes without any additional tools installed. When you gain more experience and become more familiar with the available services, you will see that Azure offers many useful preconfigured setups (such as an integrated Web Apps and Structured Query Language (SQL) Database instance), which can be used to shorten development and configure all services in one place.
Provisioning any Azure service requires going through creators consisting of different steps. In general, not all fields will be required. It is worth remembering that all the mandatory parameters are marked with an * (asterisk) symbol.
The first tab available is the Basics tab, which is divided into three different sections: Project Details, Instance Details, and App Service Plan. The very first thing is entering a combination of Subscription and Resource Group details. Remember that in Azure, resources cannot exist in a vacuum—they require a container for logical separation. Here, you can use any combination you have access to (or you were asked to choose). The process is illustrated in the following screenshot:
Figure 1.3 – Project Details section
Next, we have the Instance Details section, which requires a few more details to be provided. Here, we need to enter the name of our web application (it has to be globally unique), the method used to publish it (Code versus Docker Container), and Runtime stack, Operating System, and Region details, as illustrated in the following screenshot. While the Publish/Runtime stack/Operating System parameters seem self-explanatory and depend on your technology stack, let's talk a little bit about regions next:
Figure 1.4 – Instance details section
In Azure, each region represents a co-located set of data centers and directly affects the geographic location of your cloud resources. That also has some legal implications (if you are about to process users' data, it is often forbidden to store it outside the user's origin). Each instance of an Azure service must be deployed to one of the available regions.
Tip
One of Azure's best practices is to deploy resources to the same region as the resource group they are in. This allows for the best performance and reliability.
The last section of the Basics tab is App Service Plan. Since you are just starting with Azure, you probably do not have any App Service plans created. As we cannot create an App Service resource without an App Service plan, we will sort this now. Note that if you have an existing App Service plan, the Azure portal may automatically choose it here based on the chosen region. It will also generate a random name if there is no App Service plan available.
When you click on Create new, you will see a popup allowing you to enter the plan name. Click on it, enter the name of your new plan, and then click the OK button. It should look like this:
Figure 1.5 – Configuring an App Service plan
The last thing required here is to select the Sku and size option. This parameter will directly affect the features available for your web application, its performance, and finally, the price. To make a choice, click on Change size. Now, the Spec Picker screen should appear, presenting you with the options available, as illustrated in the following screenshot:
Figure 1.6 – Spec Picker for App Service plan
As you can see in the preceding screenshot, we have three categories of App Service plans, as follows:
Dev / Test: This contains F, D, and B tiers (which stand for free, shared, and basic). They are designed for simple development/test (dev/test) scenarios and lightweight web applications that do not need features such as autoscaling or backups. Note that the shared tier is unavailable for Linux.Production: This offers powerful machines and advanced features that are useful in many day-to-day scenarios, such as application programming interfaces (APIs), e-commerce, and popular portals.Isolated: This uses the same hardware as the Production tier, but with even more features and possibilities to isolate your web apps on the hardware level. This is the most expensive category but can be helpful when creating systems that cannot be made available publicly.Tip
It is important to remember that tiers F and D have a limited amount of computing time per day. That means that once you exceed the limit (60 minutes for the F tier, and 240 minutes for the D tier) of your processing time, your application will become unavailable and be suspended until the next day.
For this exercise, let's select any tier from the Dev / Test category. Once you are satisfied with the option you've selected, you can click the Apply button. My configuration, for example, looks like this:
Figure 1.7 – Configure App Service plan with a free tier
Tip
Remember that you can always upgrade (or scale up) the instance of your App Service plan. For example, if you need a specific feature, or the popularity of your application has grown, revisit the Spec Picker screen and choose the options that suit you the most. This is one of the biggest advantages of cloud over on-premises, where you would have to buy and set up new machines on your own.
Now, you can click Next: Deployment (Preview), which will bring us to the next tab in our creator, as follows:
Figure 1.8 – Deployment tab
This tab allows us to configure the Continuous deployment setting for our application using GitHub Actions. Unfortunately, that kind of automated deployment is beyond the scope of this book. If you want to learn more, you can read about it here: https://docs.microsoft.com/en-us/azure/app-service/deploy-github-actions?tabs=applevel. For now, we can skip this and click the Next: Monitoring button to enable monitoring of our Web Apps resource using Azure Application Insights, as illustrated in the following screenshot:
Figure 1.9 – Monitoring tab
Here, depending on the platform we chose, we can decide whether we want to enable monitoring by choosing the Yes option. Unfortunately, because my choice was Linux, the creator disables that for me (although it will be available to you if you selected Windows). Azure Application Insights will be described in detail further in this book, so to keep things simple, let's choose No.
We will skip the last tab, Tags, for now, so the only thing left is to click on the Review + create button and, after confirming all the details are correct, click on Create. If Azure detects that something is wrong with your input, it will highlight all the invalid fields and block the process of provisioning a resource.
Now, wait several seconds for the creation of a new resource. During this time, Azure will validate the template and parameters, and orchestrate multiple underlying controllers to create a service. Once a new resource is created, you should see a notification and be able to see your resources. To quickly validate this, click on the All resources button on the left and filter all of them using, for example, the name of the App Service resource you have created. The process is illustrated in the following screenshot:
Figure 1.10 – Created App Service plan visible in the Azure portal
Let's now switch our focus to creating an Azure App Service resource using a different toolset.
If you do not want to create your web apps using the Azure portal, you can use Microsoft Visual Studio, which has built-in integration for many different Azure services. As Visual Studio is an integrated development environment (IDE) designed mostly for .NET application development, all the exercises will use .NET as a development platform. For a more generic approach, please look at the next section, where we will describe working with VS Code as an alternative.
Note
This exercise was created using Microsoft Visual Studio Community 2019 (16.8.4) with Azure workloads installed. If you want to configure your instance and ensure everything is set up correctly, please follow the short tutorial available at https://docs.microsoft.com/en-us/dotnet/azure/configure-visual-studio.
In Visual Studio, click on File | New | Project. This will display a Create a new project window, where you can find plenty of different templates for starting with a new application. Because we are aiming at deploying a web application, let's choose a template for ASP.NET Core Web Application, as illustrated in the following screenshot:
Figure 1.11 – Creating a new project in Visual Studio
When a template is selected, click on the Next button in the bottom-right corner of the window. All that's left to do now is enter a project name and its location on our hard drive, as follows:
Figure 1.12 – Configuring a new project
Enter any name you feel works for you and select a location where the files will be created. When everything is ready, click the Create button. The last step is choosing a template for this application. To make things easier, we will go for Web Application as this will give us some content to work with. You can see the available templates in the following screenshot:
Figure 1.13 – Creating an ASP.NET application
Tip
You have probably noticed an Authentication section, which I have not described. It allows you to select the method used for authenticating access to your web application. We will cover that feature in the Securing App Service resources using different security providers section.
Let's leave all other options with their default values and click Create. After several seconds, Visual Studio should generate your new application, which is ready to work. To ensure that everything is correct, press the F5 button to run your website locally. After a few seconds, you should see a screen like mine here:
Figure 1.14 – Locally working application
If everything works as expected, there is one question remaining: how can we deploy it to Azure to have our website working in the cloud? Let's go back to Visual Studio for a moment and close the debugger. When you right-click on a project in Solution Explorer, you will see a context menu. There, between various menu options, click on Publish..., as illustrated in the following screenshot:
Figure 1.15 – Context menu of a project
As we are building a web application hosted in a cloud environment, our choice for the publish location will be Azure, as illustrated in the following screenshot:
Figure 1.16 – Selecting a publish target
Now, click the Next button to select a particular Azure service used for our deployment. Currently, we are getting started with Azure App Service, so options for containerization will be a no-go. You will learn more about them in the next chapters. However, depending on your desired platform, you can choose between Linux and Windows machines. If you do not have specific requirements related to your hosting environment, I recommend using Linux for our deployment. The Linux service is shown in the following screenshot:
Figure 1.17 – Publish
Let's click Next one more time. The last step is selecting an actual Azure App Service resource for the application. If you do not have one, look at the beginning of this chapter, where we went through the process of creating one in detail. After selecting the desired instance, use the Finish button to complete deployment. The process is illustrated in the following screenshot:
Figure 1.18 – Specifying a publish target
Note
If you do not see any Azure subscription, you may need to authenticate first to your cloud environment. Use the dropdown in the top right of the Publish window to select an alternative account or sign in to a new one.
Before Visual Studio sends our files, it will display a summary of the whole process. This is the last moment to reconfigure things such as target framework, deployment mode, or runtime. If everything seems fine, use the Publish button, as illustrated in the following screenshot, to publish the site to the selected Azure App Service resource:
Figure 1.19 – Publish screen summary
Once deployment is completed, you should see your web application open automatically on your default browser, as follows:
Figure 1.20 – Working application in Microsoft Azure
Congratulations! You have just created and deployed your very first App Service resource. If you look at the Uniform Resource Locator (URL), you'll see that it contains the name you set in the Visual Studio wizard. All web apps in Azure can be accessed using the following URL format: http(s)://{appservicename}.azurewebsites.net.
This also explains why a name must be unique: since, by default, all web applications hosted as Azure Web Apps resources are available publicly, you must select a name that is not already in use in another URL. In the next section, we will use the Azure CLI to deploy our application, as an alternative to using Visual Studio.
Using Visual Studio for deployments is a good idea for testing things and for development, but for sure, it cannot be used for deploying production environments. An alternative, which can be also used on our build agents (if you are using a continuous integration/continuous deployment (CI/CD) approach), is to leverage the Azure CLI. As you will see, it allows for a variety of different deployment options that should satisfy most setups.
One of the easiest options for deployment is archiving your application package as a ZIP file and sending it to Azure. To use it, you will have to prepare your application using the following structure (this is just an example; in reality, your structure will be more specific to your project):
Root
|---- Dir1
|---- Dir2
| entry_file (index.html / index.php / app.js / …)
| package_management_file (project.json / bower.json / package.json / …)
Tip
Consider using build automation instead of packaging all the dependencies into an archive. This will save both time and bandwidth when deploying an application and will make the process much safer. See the rest of this section for more details.
Once you have described the structure, you can package it using any kind of archiving tool (this can be a desktop application or a CLI command)—the important thing is to have a <filename>.zip archive that we can send using the Azure CLI. To do so, we will need to execute the following command:
az webapp deployment source config-zip --resource-group <group-name> --name <app-name> --src <filename>.zip
You will have to provide the name of your Azure App Service resource, its resource group, and the path to the archive you created. The following screenshot shows the result of running that command:
Figure 1.21 – Result of publishing a web app via Azure CLI
Once your code is pushed and extracted, a new version of your application should be available and ready to serve the newest content.
A caveat of the preceding method of deployment is the need to prepare all the build artifacts upfront and send them to Azure. There are pros and cons to that approach, as outlined here:
You are sending the final structure of your application and there are no additional steps needed, so any kind of process debugging should be minimal.Your application artifacts may be big, which can make the whole process slower as you need to pass all the files and wait until they are uploaded.As an alternative, you can enable a feature called build automation. This instructs Azure to use your project/package files and run commands such as npm install or dotnet build before running an application. To enable automation, use the following command:
az webapp config appsettings set --resource-group <group-name> --name <app-name> --settings SCM_DO_BUILD_DURING_DEPLOYMENT=true
If you enable automation, remember not to build your application on your side to avoid duplicated work.
There are some caveats of deploying your application as a ZIP file and then extracting files. As it is running, the extraction and overwriting of files may cause some undesired side effects such as locking or partial updates of the content. To avoid such artifacts, you can use a feature called Run from Package. First, you will have to enable the feature using the Azure CLI, like this:
az webapp config appsettings set --resource-group <group-name> --name <app-name> --settings WEBSITE_RUN_FROM_PACKAGE="1"
Then, we can once again use the command you are already familiar with, as shown here:
az webapp deployment source config-zip --resource-group <group-name> --name <app-name> --src <filename>.zip
Because Run from Package is enabled, instead of extracting your files, Azure App Service will mount the whole package as a read-only directory and run your application from it. As the application will be restarted, all the side effects should be mitigated.
Microsoft Visual Studio is not the only available IDE that allows you to work with Azure App Service resources. Because this Azure service supports different technology stacks, including .NET, JavaScript (JS), PHP, Java, and so on, you can easily leverage its capabilities to host different websites using different runtimes. For instance, let's assume that we have the following PHP code that displays a Hello World message:
<?php echo('Hello world from Azure App Service - PHP here!'); ?>Such a simple PHP application can be easily created in any available IDE that supports the PHP language. For this exercise, I chose VS Code, an open source editor, as it can easily be extended using many different plugins. As you can see in the following screenshot, all you need is a single file within your project directory:
Figure 1.22 – PHP project structure
To make things easier, you can install the following extensions:
Figure 1.23 – Extensions screen in VS Code
With the Azure App Service plugin installed, you will be able to easily deploy your applications from within the IDE, without the need to go to the portal or use other methods.
Note
Before the first use of these extensions, you may need to authenticate them. Follow the displayed instructions, and VS Code will connect to your subscriptions.
Before we deploy our simple PHP application, we must create an Azure App Service resource. Go to the AZURE tab (you can also use the Ctrl + Shift + A shortcut) and find the APP SERVICE section. After that, click on the Create New Web App... button, as illustrated in the following screenshot:
Figure 1.24 – AZURE extension tab with app services
The wizard is a little bit different than in Microsoft Visual Studio, as it acts similarly to a command line, where you provide all fields and information one after another. In VS Code, you will have to enter the following:
Subscription where an app should be deployedThe Azure App Service resource nameRuntime stack (.NET/Node.js/Python/PHP/Ruby/Java)App Service plan tierNote
Using the creator described previously will not give the option to select a resource group and other, more advanced settings. If you want to have full control over the provisioning process, use Command Palette (Ctrl + Shift + P) and search for the Azure App Service: Create New Web App (advanced) option.
In this example, I specified the following:
Name: handsonchapter01-codePHP 8.0Free tierOnce the provisioning is complete, VS Code will ask you whether to deploy the application. Select Deploy, and then choose a folder to deploy from, as illustrated in the following screenshot:
Figure 1.25 – Selecting a folder to deploy from
Next, you will have to select a subscription and the exact instance of the web application in Azure (VS Code may not ask you for that input if it saved your previous choices). The following screenshot illustrates this:
Figure 1.26 – Selecting a web app as a deployment target
Select the instance and confirm the new deployment. Once everything is set and ready, you will see a notification informing you that you are now able to browse the website, as illustrated in the following screenshot:
Figure 1.27 – Deployment confirmation
When you click on the Browse Website button, you will be forwarded to the web application you have just deployed. Here, you can see a working example:
Figure 1.28 – Working application in Azure
Note that this extension allows you to directly manage the service from within the IDE and gives you access to different features, including application settings, deployment slots, and even streaming logs.
The important thing here is that by using the same path, you will be able to host a variety of different runtimes inside different Azure App Service resources. It doesn't matter whether it is a Java application, a Python script, or a Node.js backend—they are all supported and can be easily developed using IDEs such as VS Code.
Currently, App Service supports a couple of different configurations when it comes to selecting the operating system, runtime, and platform. Here are some of the possible options for running your website using App Service:
.NET Core 2/3.NET 5/6ASP.NET 3.5/4.8Node.js 12/14PHP 7/8Java 8/11Python 3Static HyperText Markup Language (HTML) websiteAdditionally, you can select a platform (32-bit or 64-bit), the HyperText Transfer Protocol (HTTP) version (1.1 or 2.0), an underlying operating system (Windows, Linux, or container), or even a Java web server powering your website. Let's start by selecting a proper operating system for our application.
To select an operating system to run your web app, we must create a new application in Azure. Currently, there is no possibility to change this setting after an App Service resource is created.
Note
Be careful when planning to deploy web applications using different operating systems to the same resource group because of some hardware limitations—for example, once a Linux Azure App Service plan is deployed, you cannot create a Windows one next to it. You will need an additional resource group for that.
To create a new website, go to the beginning of this chapter, where we discussed the way to deploy a web application using the Azure portal. Once you see the creator, look at the Basics tab. The Instance Details section presents the information we are interested in, as follows:
Publish: This offers a way to deploy code or a Docker container. Choosing the Docker Container option will hide the Runtime stack parameter as it is no longer valid.Operating System: You can select either Windows (which is the most common option for .NET applications, suitable for running .NET Framework, Java, Node.js, or PHP sites) or Linux, which can be used for running an application written in .NET Core. Additionally, you can run Java, Node.js, PHP, and Python applications as well.Runtime stack: Depending on your technology stack, here, you can select exactly what you need to get started with your application.The choice is yours. Each operating system has different characteristics: Linux is perfect for running Python applications, as Windows has some performance issues regarding this language; on the other hand, you may have many websites written in .NET Framework, which is optimized for Windows systems. Each of the operating system options also has different pricing. Let's compare Windows and Linux here, assuming the West Europe region is chosen:
Figure 1.29 – App Service plan pricing comparison
As you can see, there are some differences between these two operating systems. More importantly, Linux does not currently support the Shared tier. The Isolated tier is something you should consider if in need of hardware isolation or strict network connectivity requirements. When you have considered all the pros and cons, you can create an App Service resource powered by the operating system of your choice.
In the previous section, you learned how to choose a proper operating system for your application. This is, of course, not everything needed to run a website—you must also enable a specific language if you want to deploy (for example, PHP code). To do so, go to your App Service resource (you have many options by which to do this: either choose App Service from the Azure portal menu on the left and select your Web App resource or go to the resource group you created by choosing it from the Resource Groups blade) and then select the Configuration blade, as illustrated in the following screenshot:
Figure 1.30 – Configuration blade
Initially, you could feel a bit overwhelmed by all those options available, but soon, as you gain more and more experience, all will become clear. You might have noticed the Click here to upgrade... notification here—some features, such as Scaling out or Always on, are only available from the B1 tier upward.
Tip
Remember that the Always on feature could become crucial in some specific scenarios, as it defines whether your application is always running or not (so it can become idle when no one uses it). As you will learn in the coming sections, enabling Always on is recommended when running, for example, continuous WebJobs or Azure Functions.
Currently, we are interested in all options mentioning a programming language. These options are available in the General settings tab and include the following:
.NET versionPHP versionPython versionJava versionNode versionRuby versionAs opposed to selecting the operating system, which cannot be changed later, you are free to change the stack powering your website anytime. This is unlikely in most cases, but if you ever need to do that, you will not have to recreate the whole App Service instance.
Tip
As mentioned earlier, always select the correct operating system powering your App Service instance, depending on the language that you chose for your application. While it is possible to run PHP or Python on Windows, selecting Linux is recommended as many libraries and packages can run only under this particular operating system.
Let's now check how we can work with web application settings.
The Configuration blade offers more than simply enabling or disabling available features. As you can see, you have three different tabs giving access to various features, as follows:
Application settings: This tab contains settings used by your application while running. It allows you to set parameters available as environment variables and connection strings transmitted over an encrypted channel.General settings: This tab contains settings for controlling technology stack and platform settings such as WebSocket, HTTP version, or File Transfer Protocol (FTP) access.Path mapping: This is used so you can mount Azure files/blobs and access them from within your application without additional configuration.Tip
Remember that Application settings features for .NET applications are injected at runtime and will override existing settings stored in your web.config file. When it comes to other platforms (.NET, Java, Node.js), settings from this section will be injected as environment variables to which you can refer. This is also true for Connection strings features.
Application settings features in Azure are always hidden when stored. What is more, you can easily secure them by disallowing all users from accessing them or even integrating them with Azure Key Vault for further protection.
Tip
Connection strings features for platforms other than .NET are always prefixed with the appropriate connection type. There are four possibilities: SQLCONNSTR_, MYSQLCONNSTR_, SQLAZURECONNSTR_, and CUSTOMCONNSTR_.
Now, as we learned a bit about various configuration settings, we can focus our attention on additional basic functionalities App Service offers.
We touched on this topic at the beginning of this chapter, so you should have an idea of what we are going to cover now. As you remember, when an App Service resource is created, you must select (or create) an App Service plan, which defines both available performance and additional features. Let's cover all three categories, this time focusing on the differences between each tier. To see your options without going to an Azure App Service creation screen, go to the Scale up (App Service plan) blade, as illustrated in the following screenshot:
Figure 1.31 – Scale up blade
You will see a screen where all available tiers for the App Service plan will be displayed.
App Service plans designed for development and testing environments can be found in the Dev / Test category, as illustrated in the following screenshot:
Figure 1.32 – Selecting a tier
We have three different tiers available, as follows:
Free (F1): The most basic option, with shared infrastructure, 1 gigabyte (GB) of memory available, and 60 minutes of compute per day. When using shared tiers, some features of App Service are unavailable (such as Always on). F1 is perfect for quick-testing or deploying an application for a presentation or demonstration. You will not be charged for using this App Service plan.Shared (D1): Like F1, but this also allows for setting a custom domain for your App Service resource. What is more, you can run your application four times longer than when using the Free tier. Still, this is a shared infrastructure, so some features cannot be used, and there will be other Azure customers on the same machine. Unfortunately, it's not available for Linux.Basic (B1): This is the first tier that can be considered for running production workloads. It guarantees dedicated A-series machines, and more memory and storage. It is also the first tier that you can scale—though only manually. The Basic tier comes with additional versions (B2 and B3), which provide more compute power.Note
If you are obligated to run your application in Azure in services defined by a service-level agreement (SLA), remember that you cannot use the Free or Shared tiers, as they do not support this.
In this category, there are many more options when it comes to choosing different features available. Remember that, in terms of hardware, the Basic tier offers the very same performance as the Standard tier. You can see a list of the Production category tiers here:
Figure 1.33 – List of production tiers
Here, we can choose between the following:
Standard (S1): The same A-series as B1. What we are getting here is autoscaling, staging slots, backups, and the possibility to use Traffic Manager (which will be described in the coming chapters). This used to be the best tier for most production applications, as it supports blue-green deployment scenarios and can handle a bigger load (thanks to integration with Traffic Manager). Currently, the price/value ratio is in favor of Premium tiers.Premium (P1v2): Offers better performance and higher limits when it comes to scaling (a maximum of 20 instances, compared to 10 in Standard) and staging slots. You also have the option to choose P2 or P3. If you need the best price/value ratio, this is the tier you are looking for.Tip
Remember that the maximum number of instances when scaling out in particular tiers is subject to availability. In most cases, these are only soft limits that can be raised after contacting support.
In general, Standard should meet most requirements when it comes to performance, reliability, and automation possibilities. However, if you are going to run a very popular website in Azure, you may need Premium, as this offers more flexibility and better scalability.
Note
One of the most important things to remember is how scaling affects pricing. In general, you have two options: either you scale up (changing tier to a higher one) or scale out (by deploying multiple instances of the same application). If you are paying, for example, $40 for an S1 instance, when you scale out to 10 instances, you will pay $400 in total—$40 for each instance running.
Sometimes, you need even more than the Premium tier has to offer. Maybe you must isolate your application from an external network. Maybe you would like to isolate it on a hardware level. Maybe 20 instances are still not enough. Therefore, Microsoft introduced the Isolated category, which is a slightly different tier as it requires you to deploy the Azure App Service environment first and then provision isolated instances that will use it. This category is shown in the following screenshot:
Figure 1.34 – Isolated tiers for App Service plan
In this category, we have only one tier divided into three versions, as follows:
Isolated (I1V2/I2V2/I3V2): It has the same virtual machines (VMs) as in the Premium tier (DV2). It also includes huge storage to store your files (1 terabyte (TB)), private app access, an integrated virtual network (so that you can access, for example, internal applications), and a more stable environment. This is the most expensive tier but offers the most when it comes to functionality and the range of features provided.Tip
In general, the Isolated tier is the most stable one when it comes to handling a huge load. While Standard or Premium tiers become unresponsive quickly when utilization hits 100%, Isolated App Service resources need more time to return the HTTP 503 Service Unavailable response. Take this into account if you need a reliable service that cannot be broken easily.
However, there is one thing worth remembering here—besides paying for each isolated instance, purchasing an Isolated plan will also require paying a stamp fee. A stamp fee is a price for isolating your hardware from other Azure customers. As of now, the cost is ~$1,071/month.
To avoid paying the stamp fee, you can buy an upgraded Isolated V2 plan. This eliminates additional costs due to the redesign of the underlying infrastructure. As for now, the cost for an I1 instance of the upgraded plan is ~$412.45/month.
After describing details of different tiers of Azure App Service plans, we can now switch our attention to security providers that web apps offer and how they can integrate with your application.
Most web applications must be secured in some way, either by using your own security system or third-party identity providers (IdPs), such as Facebook, Google, or Twitter. While working with the traditional application hosted on-premises, you often must configure everything on your own. PaaS solutions, such as Azure App Service, already possess this functionality and make it easily accessible, thanks to the Authentication feature. In this section, you will learn how to set this up so that users will be prompted to log in.
As with most PaaS services, you can configure the features of App Service directly from the portal. Thanks to such an approach, you have all options in one place and can easily switch between them.
Go to your App Service resource and then find the Authentication blade on the left, next to Configuration, as mentioned previously. When you click on it, you will see a screen for configuration, as illustrated here:
Figure 1.35 – Authentication blade
As you can see, it is currently disabled. When you click the