The Developer's Guide To Azure: Second Edition
The Developer's Guide To Azure: Second Edition
The Developer's Guide To Azure: Second Edition
Guide to Azure
Second Edition
PUBLISHED BY
Microsoft Press
A division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any
form or by any means without the written permission of the publisher.
Microsoft Press books are available through booksellers and distributors worldwide. If you need
support related to this book, email Microsoft Press Support at mspinput@microsoft.com. Please tell us
what you think of this book at http://aka.ms/tellpress.
This book is provided “as-is” and expresses the author’s views and opinions. The views, opinions and
information expressed in this book, including URL and other Internet website references, may change
without notice.
Some examples depicted herein are provided for illustration only and are fictitious. No real association
or connection is intended or should be inferred.
Microsoft and the trademarks listed at http://www.microsoft.com on the “Trademarks” webpage are
trademarks of the Microsoft group of companies. All other marks are property of their respective
owners.
Chapter 1: The Developer’s Guide to Azure ........................................................................................... 1
Introduction ............................................................................................................................................................................... 2
Information technology as a utility, not a burden ................................................................................................. 2
Computing as a utility ....................................................................................................................................................... 2
Cloud computing deployment types ............................................................................................................................... 4
The public cloud .................................................................................................................................................................. 4
The private cloud................................................................................................................................................................. 4
The hybrid cloud ................................................................................................................................................................. 4
Demystifying the types of cloud computing ................................................................................................................ 4
Infrastructure as a service ................................................................................................................................................ 5
Platform as a service .......................................................................................................................................................... 5
Function as a service .......................................................................................................................................................... 6
Software as a service.......................................................................................................................................................... 6
Why Azure? ................................................................................................................................................................................ 6
Azure has global reach ..................................................................................................................................................... 8
Azure is extremely resilient ............................................................................................................................................. 8
Azure is compliant with almost every industry ....................................................................................................... 9
Azure focuses on capabilities for developers .......................................................................................................... 9
Azure is open and supports the frameworks of your choice ............................................................................. 9
You can monitor your Azure services on the go ................................................................................................. 10
We are here if you need help .......................................................................................................................................... 10
Chapter 2: Getting started with Azure .................................................................................................. 11
Your IDEs and editors are welcome ............................................................................................................................... 11
Use the Azure command-line interface for scripting ............................................................................................. 11
Run anything on Azure ....................................................................................................................................................... 12
What about costs? ........................................................................................................................................................... 12
Selecting the right Azure services .................................................................................................................................. 12
ii Contents
Where to host your application.................................................................................................................................. 12
What to use when? .......................................................................................................................................................... 17
Making your application faster ....................................................................................................................................... 18
Azure Content Delivery Network ............................................................................................................................... 18
Azure Redis Cache ........................................................................................................................................................... 18
Azure Traffic Manager .................................................................................................................................................... 19
Where to store your data .................................................................................................................................................. 20
Chapter 3: Adding intelligence to your application ............................................................................ 24
Azure Search ........................................................................................................................................................................... 24
Azure Cognitive Services.................................................................................................................................................... 25
Azure Bot Service .................................................................................................................................................................. 25
Using events and messages in your application ...................................................................................................... 26
Azure Service Bus ............................................................................................................................................................. 26
Azure Event Hubs ............................................................................................................................................................. 27
Azure IoT Hub.................................................................................................................................................................... 27
Azure Event Grid ............................................................................................................................................................... 27
What to use when? .......................................................................................................................................................... 28
Chapter 4: Securing your application .................................................................................................... 29
Azure Active Directory ........................................................................................................................................................ 29
Azure API Management................................................................................................................................................. 29
Azure Key Vault ................................................................................................................................................................. 30
Azure DDoS protection .................................................................................................................................................. 30
Azure Web Application Firewall ................................................................................................................................. 30
Default encryption of data ........................................................................................................................................... 31
Chapter 5: Where and how to deploy your Azure services ................................................................ 32
The DevOps mind-set ......................................................................................................................................................... 32
Azure Resource Manager Templates ....................................................................................................................... 33
Azure Service Fabric ........................................................................................................................................................ 33
Containers in Azure ......................................................................................................................................................... 34
Azure Stack ......................................................................................................................................................................... 34
Where to deploy, when? .................................................................................................................................................... 35
Chapter 6: A walk-through of Azure ..................................................................................................... 36
Walk-through #1: the Azure portal ............................................................................................................................... 36
Tiles in the Azure portal ................................................................................................................................................. 36
Creating a new virtual machine .................................................................................................................................. 38
Walk-through #2: developing a Node.js web app with MongoDB on Azure ............................................... 42
Creating the web app and database using the Azure portal .......................................................................... 42
Walk-through #3: create a backend for your mobile app with Azure ............................................................. 50
iii Contents
Create a mobile app through the Azure portal .................................................................................................... 50
Additional features and moving to production ................................................................................................... 54
Chapter 7: Using the Azure Marketplace .............................................................................................. 55
How can the Azure Marketplace help me as a developer? .................................................................................. 55
Azure Solutions ................................................................................................................................................................. 55
Summary and where to go next ......................................................................................................... 56
Keep learning with an Azure free account ........................................................................................ 56
About the authors .................................................................................................................................... 57
iv Contents
1
The demand for software and related services today is greater than ever
before and this trend will only continue – exponentially so – as applications
of all sorts more and more become a part of every aspect of our daily lives.
You, as a developer, are the “magician” who is bringing this digital
revolution to your users and that’s not easy. Besides creating the unique
tangible features that your software offers, there are so many behind-the-
scenes elements that you need to take care of: your applications need to
be highly available, performant all over the world, function seamlessly on
a wide range of devices, be secure and be able to run at massive scale for
a reasonable price. These challenges are common across most software
and most industries. The solutions, however, are ephemeral things that
we keep reinventing, and they can be difficult and costly to build and
maintain.
We created The Developer’s Guide to Azure to help you on your journey to the cloud, whether you’re
just considering making the move or you’ve already decided and are underway. This eBook was
written by developers for developers. And it is specifically meant to give you, as a developer,
a fundamental knowledge of what Azure is all about, what it offers you and your organisation
and how to take advantage of it all.
The second half of the guide walks you through scenarios such as a tour of the Azure Portal and
creating a Virtual Machine. We also discuss developing and deploying a web application that
uses Node.js and MongoDB. We cover typical tasks such as CI/CD (Continuous Integrations and
Continuous Deployment), staging environments, scaling, logging and monitoring. We wrap up
by creating a backend for your mobile application that includes authentication and offline
synchronisation.
Who today would think that having a mini-generating plant outside each home and business would
be an efficient model for the distribution of electric power? We are accustomed to simply flipping
a switch to turn on a light and then we go about doing what we need to do; you certainly would never
dream of having to buy, install and maintain all of the equipment needed to illuminate your home or
office. Instead, you pay your local electric company for the power you consume every month and you
never need to concern yourself with the physics of generating electricity, dealing with the capital
expense, maintaining the equipment, repairing it after storms – nothing. Just flip the switch and be
productive at something else.
Well, just as you neither need nor want to know exactly how electricity is delivered to your house,
neither do you need to know exactly how the computing power and services that you consume in
the cloud are made available to you. Someone else takes care of that for you. Thus, first and foremost,
moving your compute, storage and network to the cloud provides ease of use, just like turning on
a lamp. And you pay only for what you use, in the same manner as you pay only for the electricity
you use to power your home.
Of course, moving beyond our analogy, the cloud offers many more specific benefits for your IT
operations, like scalability and the ability to use intelligent services like search and facial recognition
in your applications, to name just two.
Computing as a utility
So, ultimately, you can think of cloud services such as Azure as computing as a utility. Of course,
Azure offers far more in the way of products and services than the local electric utility does, so cloud
computing can sometimes be difficult to clearly define. In fact, some say that the cloud is basically
just using somebody else’s computers, which is technically true, but the cloud is so much more:
The cloud is a system that provides robust, resilient, intelligent services and
compute resources at infinite, elastic, global scale.
The cloud and Azure provide services that help you to accomplish so many things: from the mundane,
such as adding Search to your application, to the more exotic, such as implementing Continuous
Integration (CI) and Continuous Deployment (CD) workflows. You can automatically tune your
database or set up push notifications to mobile devices, easily and quickly. These are just a few
examples of some common things that developers have created for themselves over and over again,
but are now available as a service. This makes it possible for you to use these services with very little
effort – almost like flipping a light switch! You can then focus on the pieces of your application that
make it unique; the features that provide real added value for your users.
As we stated a moment ago, the power of the cloud is that services and resources are incredibly
robust and resilient. It is very unlikely that they will fail to run. This is because the cloud is smart.
It is self-healing and, as is the case with Azure, there are datacentres all over the world, filled with
tens of thousands of servers. If one server fails, another takes over. If an entire datacentre were to
fail (a highly unlikely scenario in and of itself), another would take over. All of this is possible because
of the massive scale of the cloud.
One of the most compelling arguments in favour of the cloud is that you can scale-up your services
and resources almost infinitely, and certainly to a degree that you simply can’t do with on-premises
resources, unless you’re prepared to spend enormous sums of money on capital equipment and
staffing to administer it all. And, you can scale globally. You can put your services anywhere in the
world so that you can provide a performant experience to your users, regardless of where they are.
It also means that you can keep your data where you need it to be.
Perhaps most important, though, when you use cloud resources, you can scale-back your services
and resources when there is no longer high demand. Returning again to our electric utility analogy,
if you’re having many friends and relatives to your house for a party, you’re going to turn on a lot
of lights inside and outside the house, use your microwave oven frequently, turn on some music and,
generally, consume more electricity. But when the party is over and your guests have left, your power
usage returns to normal, and so does your billing. It’s the same thing when you take advantage of the
cloud and Azure: you pay only for what you use, not for what you might need when usage is high.
More information To learn about the Azure portal and create your first VM, go to
https://docs.microsoft.com/azure/virtual-machines/windows/quick-create-portal.
In addition to massive scalability, off-the-shelf intelligent services and pay-per-use efficiency, the
cloud offers increased security.
The cloud is used by millions of people, 24×7, worldwide; of course, it is attacked by many people,
as well. Reputable and experienced cloud providers like Microsoft know the usage patterns of normal
users versus those of malicious actors. This means that it knows how to protect against both the
most common and most unique attacks out there. Intelligent monitoring tools, machine learning
algorithms and artificial intelligence give cloud providers the ability to detect attacks in real time
and stop them in their tracks.
Decades of experience in security and massive-scale traffic, combined with top industry security
expertise, make the cloud a much more secure environment than any on-premises datacentre.
More information To read more about how Azure secures your applications and data,
go to How Azure Security Centre detects DDoS attack using cyber threat intelligence,
Azure Security Overview and How Microsoft deals with cybercrime.
We’ve briefly explored the question of why you want to begin the migration to the cloud and Azure.
Now, let’s examine the cloud’s major components, what they do and how they fit into the grand
scheme.
But, how do you set up a private cloud platform in a traditional on-premises datacentre? Fortunately,
Azure provides a unique solution designed specifically to work in this environment: Azure Stack. In
a nutshell, Azure Stack is your own private instance of Azure in a box that you can run in your on-
premises datacentre.
Running services in a private cloud is not the same as running services in your on-premises
datacentre. Azure Stack offers all of the advantages of Azure, including intelligent services that you
can use in your applications, all within the confines of your on-premises datacentre. Thus, if for special
security or governance reasons you need to keep certain operations “close to home” in your on-
premises datacentre, you can still enjoy all of the benefits offered by Azure and the cloud paradigm.
Azure provides solutions for all cloud computing deployment types. This gives businesses more
freedom to use Azure where and how they want to. And they can determine the amount of control
that they want to have over their applications and data.
Infrastructure as a service
With infrastructure as a service (IaaS [pronounced “eye-as”]), you are responsible for everything,
except the hardware. Azure takes care of all the hardware, such as the solid-state drives (SSDs),
network cabling, routers, power supplies, backup generators, cooling systems and so on. Services that
fall into this category include Azure Virtual Machines, Azure Virtual Networks and Azure Containers.
You take care of everything else. Your application, patching of the operating system (OS), logical
network configuration and even keeping antivirus programs on the machines up to date. This means
that you maintain total control over these elements. But, it also means that you spend a lot of time
and effort keeping the services and resources running and less time working on adding business value
to your core application products.
Platform as a service
Using the platform as a service (PaaS [pronounced “pahz”]) model, you are responsible for your
application and its configuration; Azure provides the OS and hardware. As Figure 1-1 demonstrates,
PaaS is an abstraction level higher than IaaS. You have far fewer responsibilities, but less direct control
over your hardware resources than with IaaS. Services that fall into the PaaS category include Azure
App Service, Azure SQL Databases, Azure Redis Cache and Azure Batch.
You deploy your application and configure it. You also do basic server configuration, like scaling the
pricing tier or the number of instances on which your app runs. Your application still runs on a server
somewhere, but you aren’t responsible for that server (nor do you have any control over it), which
means that you can spend much more time concentrating on adding business value to your
applications and less time keeping a server running.
Try it out Create a Node.js application with a MongoDB on Azure in this walk-through
at https://docs.microsoft.com/azure/app-service/app-service-web-tutorial-nodejs-
mongodb-app.
Function as a service
In function as a service (FaaS [pronounced “fahz”]), you are responsible only for your application and
your business logic. You don’t need to worry about scaling, the OS or any of the hardware. FaaS is
sometimes called serverless computing. Services in the FaaS category are Azure Functions, Azure Logic
Apps and Azure Event Grid.
In FaaS, all you need to do is create your application or weave together business logic and run it.
Scaling happens automatically. One of the more noteworthy benefits of FaaS is that you pay for the
resources you use only when the logic runs instead of paying for a service that is always on, waiting
for somebody to use it.
But FaaS does more than just host your application; it connects your logic to triggers and sources.
Outside sources such as Azure Storage Queues or WebHooks can initiate Azure Functions or Logic
Apps and provide them with data to process. You do not need to write the activating logic or set up
the plumbing to connect to external data stores or services, meaning you can focus on your logic and
customer-facing features.
Software as a service
With software as a service (SaaS [pronounced “sass”]), you need only concern yourself with
configuring the software – nothing else. Indeed, SaaS is the highest abstraction level of the cloud
computing types. Services in the SaaS category include Azure Cognitive Services and Azure IoT Suite.
Office 365 is another example of an Azure SaaS application suite, offering reliable business
applications such as Microsoft Word, Excel, PowerPoint and more. And all of this is available
without you having to install or maintain anything.
With SaaS, the software is ready to use. All you need to do is configure it to your preferences and then
you are ready to go. You don’t write the software and you don’t need to think about deployment,
scaling, operating systems and hardware.
Why Azure?
So, you’re thinking the cloud might be what you need for your company to create incredible software
products and deliver the value and user experience your customers expect. Certainly, the Azure cloud
platform can help you accomplish that. With its vast resources and compute power, plus a wide array
of intelligent services, you can build highly scalable, dynamic apps and pay only for what you use. But
there are many cloud vendors out there today, each offering unique capabilities and products. So,
again, why Azure?
Deliver cross-platform software experiences, like mobile, desktop, web and hybrid
experiences: Azure provides services with which you can implement these scenarios “out of the
box,” like Azure App Service, including Web App and Mobile App, and Mobile Centre and Visual
Studio Team Services for delivering and managing all application types.
Deliver services wherever they need to be: Azure is unique in its breadth of deployment
options: the public cloud, hybrid solutions and Azure on-premises, in your own datacentre (via
Azure Stack). All of these options can provide massive scale at an affordable price, while keeping
your data where it needs to be.
Deliver an intelligent, massive scale, data platform: Azure has many services that you can
use to capture, store, analyse and present your data. These are services like Azure SQL Databases,
Data Lake Store and Data Lake Analytics, HDInsight, Event Hubs, Cognitive Services and many
more. All of these services can create an affordable, intelligent and massively scalable data
platform that gives businesses the tools to extract valuable insights from the vast amount of data
being churned out today.
Deliver high-quality software, fast: You need to test always and fail fast to deliver quality
software. With Azure, you can do so through integrated CI and CD mechanisms directly in services
like Web App or through Visual Studio Team Services. Features like App Services Deployment
Slots make it possible for you to deliver fast, with no downtime. And, to know that your app is
working as expected in production, Azure provides monitoring services, like Application Insights,
that let you know exactly how your app is doing and where you can improve.
If you use Content Delivery Networks (CDNs) to reduce latency, the chances are that there is an
Azure datacentre in close proximity to where your customers are and where you need to deliver
their content. Another benefit that Azure can offer with so many facilities in so many locations is that
you have a wider range of choices for data storage. This can help you to ensure that your company
remains in compliance with local or regional regulations and laws with respect to data sovereignty.
Microsoft continues to invest heavily in datacentre infrastructure and innovation through open-source
hardware development and novel new datacentre solutions such as the underwater datacentres from
project Natick.
As we mentioned earlier, Microsoft has been operating datacentres and providing IT services at
massive scale since 1989. It has accumulated a lot of knowledge in that time. Today, Microsoft has
some of the best minds in the IT industry working continuously to keep Azure up and running so that
you can rely on it for hosting your services and storing your data. That’s why all of the Azure services
have SLAs to back that up.
For instance, by complying with the ISO 27001 certification, Microsoft guarantees that it implements,
monitors, maintains and continually improves its security standards for its global network of
datacentres as well as for the individual services in Azure.
Azure even has a specific offering for US government customers called Azure Government, which
is basically a “special edition” of the Azure cloud that addresses the unique needs of government
entities. Azure Government is run separately from the Azure public cloud, in its own instance, meaning
that it runs on separate, dedicated servers on a completely separate and isolated infrastructure.
Additionally, you can choose the ecosystem you prefer. Azure supports most operating systems,
like Linux and Windows, and you can script everything using Bash if you want. You can also run
your application how you want – using containers, Azure Service Fabric, App Services, Azure Stack
and so on.
After you have learnt how to use Azure with one toolset, you can use it with any other toolset.
The services and the Azure portal work the same for everything.
Additionally, there are services in Azure that perform smart detections and recommendations for
your services and can send you alerts about them. These are things like detecting that a web app
is running slower than usual or informing you that an App Service scaled up automatically. Azure
Security Centre and Azure Monitor are some of the services that can alert you about these things
so that you never have to miss anything important.
You can buy a support plan, that gives you access to the Azure technical support teams and provides
other services like guidance based on best practices to design for the cloud or assistance in planning
your migration. Depending on your needs, you can buy a support plan that guarantees responses
from the technical support teams within 15 minutes.
Additionally, you can get help for free, 24×7, through many channels. You can tweet to
@AzureSupport or reach out to the support teams through MSDN forums, StackOverflow,
Reddit or the Microsoft Tech Community.
Plug-ins are available for all the popular IDEs, giving you the ability to do things like publish directly
to Azure. And even if you prefer using a bare-bones tool like Notepad, you can still automate your
deployments to Azure using Continuous Integration (CI)/Continuous Delivery (CD) practices.
You can use the Azure CLI available on the Azure portal in the Azure Cloud Shell, or locally, on your
machine, through the Azure CLI tooling. Another advantage is that you can apply your existing Bash
or Windows PowerShell expertise in the Azure CLI.
Note The Azure Pricing Calculator estimates costs for pay-as-you-go subscriptions.
There are other payment options for enterprises, partners and MSDN subscribers,
which can affect the costs of services.
You can also keep an eye on your costs using the Azure Billing APIs and Pricing alerts. You can take
advantage of these to gain insights into costs and spending trends so that you can control your costs.
VMs
One of the ways to host your application is in a VM in Azure Virtual Machine. This provides you
with a lot of control over how you host your application, but you are responsible for maintaining the
environment, such as patching the operating system (OS) and keeping antivirus programs up to date.
You can, for instance, use an VM to test the latest preview version of Visual Studio, without getting
your machine “dirty”.
Azure Batch
If you need to run large-scale batch or high-performance computing (HPC) applications on VMs,
you can choose Azure Batch. Batch creates and manages a collection of up to thousands of VMs,
installs the applications you want to run and schedules jobs on the VMs. You do not need to deploy
and manage individual VMs or server clusters. Batch schedules, manages and auto-scales your jobs,
so you use only the VMs you need. Batch is a free service; you only pay for the underlying resources
consumed, such as the VMs, storage and networking.
Batch is well suited to run parallel workloads at scale such as financial risk models, media transcoding,
VFX and 3D image rendering, engineering simulations and many other compute-intensive
applications. Use Batch to scale out an application or script that you already run on workstations
or an on-premises cluster, or develop SaaS solutions that use Batch as a compute platform.
Containers
Containers are much more lightweight than VMs and you can start and stop them in a few
seconds. Containers also offer tremendous portability, which makes them ideal for developing
an app locally, on your machine, and then hosting it in the cloud, in test, and later in production.
You can even run containers on-premises or in other clouds – the environment that you use on your
development machine travels with your container, so your app always runs in the same ecosystem.
Just like VMs, containers provide you with a lot of control over your environment. You can install what
you need to run your applications. But, again, you are responsible for patching and maintaining the
OS that runs in the container and for ancillaries like antivirus programs.
The Container Instances service is billed per second, per virtual CPU, per gigabyte or by memory usage.
More information To learn more about Container Instances, go to Get started with
Azure Container Instances.
More information To learn more about Container Service, go to Get started with
Azure Container Service.
Azure Functions
With Azure Functions, you can write just the code you need for a solution without worrying about
building a full application or the infrastructure to run it. A function is a unit of code logic that is
triggered by an HTTP request, an event in another Azure service or based on a schedule. Input
and output bindings connect your function code to other services, like Azure Blob Storage, Azure
Cosmos DB and Azure Service Bus, with minimal code. Using Functions, you can build small pieces
of functionality quickly and host them in an elastic environment that automatically manages scaling.
Another thing that makes Azure Functions special is that you can choose to pay only for functions
that run, without having to keep compute instances running all month. This is also called serverless
because it requires only that you to create your application and not deal with any servers or even
scaling of servers.
You can write Azure Functions in C#, F#, Node.js, Java, PHP and a growing list of languages.
An example of an application that uses Functions is one that activates a function every time a new
image file is uploaded to Azure Blob Storage. The function would then resize the image and write
it to another Blob Storage account. The function signature for this example would look like this
(in C# script):
Data from the Blob that triggered the function is passed into the function as the myBlob parameter,
which includes the Blob URL. You can use outputBlob output binding parameter to specify the Blob
to which to write the result. There’s no need to write the plumbing for connecting to Blob Storage,
you just configure it.
Try it out Create your first Azure Function using the Azure Portal.
Just like Azure Functions, Logic Apps are serverless, are scaled automatically and you pay for them
only when it runs.
1. The Logic App is activated by an email containing a shipping order that arrives in Office 365.
2. Using the data in the email, the Logic App checks on the availability of the ordered item in
SQL Server.
3. The Logic App sends a text message to the customer’s phone using Twilio (the phone number
was also in the email), indicating that the order was received and the item has been shipped.
Web App: Web App is one of the most widely used Azure services. You can use this to host
your web applications or APIs. A Web App is basically an abstraction of a web server, like Internet
Information Services (IIS) or Tomcat, that you use to host HTTP-driven applications.
Web App can host applications that are written in .NET, Node.js, PHP, Java or Python, and there
are extensions that you can use to run even more languages.
Try it out We walk you through a sample Node.js and MongoDB app in our example
section.
Try it out We walk you through deploying a web app with a Docker formatted
container in our example section.
Mobile App: Mobile App provides a backend for your mobile applications. You host an API in
Mobile App that your mobile applications connect with through the cross-platform client SDK.
This is available for iOS, Android, Windows and Xamarin for iOS and Android and Xamarin Forms.
Mobile App provides unique features like Offline Sync and Push Notifications that help you to
create a modern, well performing and secure mobile experience.
Try it out We walk you through creating a mobile backend in our example section.
Scaling
Azure App Service runs on App Service Plans, which are abstractions from VMs. One or more VMs run
your Azure App Service, but you don’t need to know which ones because Azure takes care of them.
You can, however, scale the resources that run your Azure App Service. You can either choose a higher
pricing tier (ranging from free to premium) or increase the number of application instances that are
running. You can even have Azure App Service automatically scale the number of instances for you,
based on a schedule or metrics like CPU, memory or HTTP queue length.
Deployment slots
This is a very useful feature of Azure App Service. You can deploy a new version of your application to
a deployment slot, where you can then test whether it works as expected before moving it into your
production slot. You can even use Azure’s Testing in Production feature to route a percentage of traffic
from your production app to a deployment slot. For instance, you could shunt 10% of your users to
the new version of your app in the deployment slot to see whether the new features are functioning
as expected and whether users are actually using them.
After you are satisfied with how the new version of your app is performing in the deployment slot,
you can carry out a swap, which exchanges the app in the deployment slot with that in your
production slot. You can also swap from a development slot to a staging slot, and then to the
production slot, as illustrated in Figure 2-1. Before doing this, the swap operation verifies that the
new version of your website is warmed up and ready to go. When this has been confirmed, the swap
operation switches the slots and your users now see the new version of the app, with no downtime.
If you want, you can also swap back, reverting the deployment of the new version.
You use deployment slots within an environment like Development, Test or Production. You don’t use
deployment slots as environments, because they all reside in the same App Service Plan, and you want
those to be separated for security, scaling, billing and performance.
You can swap deployment slots manually, through the Azure command-line interface (CLI) and
through the Azure Management API. This allows tools like Visual Studio Team Services to perform
swap operations during a release.
A deployment slot is another element of Azure App Service (like a Web App) that runs in the same
Azure App Service Plan, next to your original Azure App Service. Because deployment slots run in the
same Azure App Service Plan as your original Azure App Service, they don’t cost anything extra to use.
Continuous Delivery
To publish your application to App Services, you can use external services such as Visual Studio Team
Services, Jenkins or Octopus Deploy. You also can use the Continuous Delivery (CD) feature in App
Services. This makes it possible for you to create a build-test-release pipeline right in the App Service.
The process does the following:
1. Retrieves the latest source code from the repository that you indicate
2. Builds the code according a template that you pick (ASP.NET, Node.js and so on)
3. Deploys the app in a staging environment and load-tests it
4. Deploys the app to production after approval (you can indicate whether you want to use
a deployment slot)
Additionally, you can ensure that your application is served over HTTPS by using a Secure Sockets
Layer (SSL) certificate. You can bring your own certificate or buy one directly from the Azure portal.
Try it out See how to purchase and configure a certificate in this walk-through.
To isolate these support services from the internet, you can use an Azure Virtual Network. This service
wraps your support services and connects them to your app in Web App in such a way that the
support services are exposed only to the app, not to the internet. This article describes this service
in more detail and shows you how to use it.
Sometimes, you might want even more control. Maybe you want your app to be wrapped in a Virtual
Network so that you can control access to it. Perhaps you want it to be called by another app in
Web App and have it be a part of your backend. For this scenario, you can use an Azure App Service
Environment. This affords you a very high scale and gives you control over isolation and network
access. Note, though, that App Service Environment is available for App Services in the premium
pricing tiers only.
Note App Service Environment currently doesn’t work for Web App for Containers.
Table 2-1 briefly outlines the categories of app services available and what purposes they can be used for.
It offloads serving content from your application. It is now served by Content Delivery Network,
thereby freeing up processing cycles for your application
It brings static content physically closer to your users by distributing it to PoPs all over the world
You can benefit from Content Delivery Network in web applications, but also in mobile and desktop
applications.
An example of using Content Delivery Network is to serve videos for a mobile app. The videos can
be large and you don’t want to store them on the mobile device (nor do your users!). Using Content
Delivery Network, they are served from the PoP, which also improves performance, because it is close
to the user.
To eliminate some of these “roundtrips,” you can cache data that doesn’t change often. This way,
instead of querying the database every time, you could retrieve some of the data from a cache, like
Azure Redis Cache. The benefit of the cache is that it stores data in a simple format such as key–value.
You don’t need to run a complex query to get this data, you just need to know the key to retrieve the
value. This can improve the performance of your application dramatically. Here’s how this workflow
operates:
1. The app needs some data and attempts to retrieve it from the cache.
2. If the data is not there, the app gets it from the database and also stores the data in the cache.
3. The next time the app is looking for that particular piece of data, it will find it in the cache, saving
a trip to the database.
Azure provides Cache-as-a-Service with Redis Cache. This is based on the open-source Redis project
and is now backed by Microsoft engineers and SLAs. It performs very well and has advanced options
like clustering and geo-replication.
Azure Traffic Manager scales across regions which helps to reduce latency and to provide users
a performant experience, regardless of where they are. Traffic Manager is an intelligent routing
mechanism that you put in front of, for instance, your Web App applications, all over the world.
Web App acts as endpoints, which Azure Traffic Manager monitors for health and performance.
As Figure 2-2 demonstrates, when a user accesses your application, Traffic Manager routes her
to the best performing Web App application in her vicinity.
Including Traffic Manager in your architecture is a great way to improve the performance of your
application.
Figure 2-2: Azure Traffic Manager directs traffic to the closest and best performing endpoint
PostgreSQL
Cosmos DB
Warehouse
SQL Data
MySQL
Queue
Table
Blob
Disk
File
Relational data X X
Object-relational data X
Unstructured data X X
Semi-structured data X
Queue messages X
Files on disk X
High-performance files on disk X
Store large data X X X X X
Store small data X X X X X X X X
Geographic data replication X X
Note You can use almost all of the storage options mentioned in this section
as activators and bindings for Azure Functions.
You can use SQL Database with your favourite tools, including SQL Server Management Studio and
the Entity Framework.
Geo-replication, which replicates data to other geographical regions in real time (Get started with
geo-replication)
Dynamic data masking, which dynamically masks sensitive data for certain users at runtime
(Get started with dynamic data masking)
Auditing, which provides a complete audit trail of all the actions that happen to the data
(Get started with Azure SQL Database auditing)
Just as with SQL Database and Azure Database for PostgreSQL, incremental backups are made every
five minutes and full backups are performed every hour, which you can use to recover your data to
an earlier state as far back as 35 days.
Database for PostgreSQL is a managed service that has the same characteristics as Database for
MySQL. You can scale it up and down, it is highly available (99.99% SLA) and it is automatically
backed up.
Try it out Create an Azure Database for PostgreSQL using the Azure CLI.
Azure Cosmos DB
Azure Cosmos DB is the new version and rebranding of DocumentDB – and more. Cosmos DB
is a new kind of database that is truly made for the cloud. Here are some of its key features:
A 99.99% SLA that includes low latencies (less than 10 ms on reads; less than 15 ms on writes).
Geo-replication, which replicates data to other geographical regions in real time (How to
distribute data globally with Azure Cosmos DB).
Traffic Management, which sends users to the data replica to which they are closest.
Limitless global scale; you pay only for the throughput and storage that you need.
In addition to all of these features, Cosmos DB offers different APIs with which you can store and
retrieve data, including SQL, JavaScript, Gremlin, MongoDB and Azure Table Storage. Different APIs
handle data in different ways. You can use documents as data as well as unstructured tables, graphs,
blobs and so on. You use the API that fits your needs and Cosmos DB takes care of the rest.
You benefit from cloud-grade performance, scalability and reliability and still use the programming
model to which you’re accustomed.
Azure Storage
Another option you have for storing data is Azure Storage. This is one of the oldest and most reliable,
well performing services in Azure. Azure Storage offers five types of storage that all benefit from the
following shared features:
Geo-redundancy that replicates data to different datacentres so that you can recover it in the
event that a disaster causes an individual datacentre to fail
Encryption of data at runtime
Custom domains
The four Azure Storage types are Blob, Queue, File and Disk (Figure 2-3).
Blob Storage
You can use Azure Blob Storage to store large unstructured data – literally, blobs of data. This can be
video, image, audio or text, or even virtual hard drive (VHD) files for VMs.
There are two types of Blobs: Page and Block Blobs. Page Blobs are optimised for random read
and write operations. These are perfect for storing a VHD. Block Blobs are optimised for efficiently
uploading large amounts of data. These are perfect for storing large video files that don’t change
often.
Queue Storage
Azure Queue Storage is an unusual type of storage in that it is used to store small messages of data,
but its main purpose is to serve as a queue. You put messages in the queue and other processes
pick it up. This pattern decouples the message sender from the message processor and results in
performance and reliability benefits. Azure Queue Storage is based on the Microsoft Message
Queueing that you can find in previous versions of Windows.
Disk Storage
Azure Disk Storage is similar to File Storage, but is specifically meant for high I/O performance.
It is perfect for use as a drive in a VM that needs high performance, like a VM that runs SQL Server.
Note, though, that Disk Storage is available only in the premium pricing tier of Azure Storage.
Unlimited storage capacity. A single file can be larger than one petabyte in size – 200 times larger
than other cloud providers offer.
This is a very different approach from the traditional data warehouse, in which you define data
schemas upfront.
For instance, you could use a Data Lake Store to store all of the data that you get from your Internet
of Things (IoT) devices that are collecting temperature data. You can leave the data in the store and
then filter through it and create a view of the data per hour, or per week. Storing the data in Data Lake
Store is quite inexpensive, so you can keep years of data there at a very low cost.
Try it out Get started with Azure Data Lake Store using the Azure portal.
Because SQL Data Warehouses run in Azure, you can use advanced features like automatic threat
detection, which uses machine learning to understand the patterns of your workload and serve as
an alarm system to alert you of a potential breach.
An example of using SQL Data Warehouse is when you know which reports you want to show to
users and know what the data schema for these reports is. You can then create schemas in SQL Data
Warehouse and populate them with data so that users can navigate through the data.
Hosting your application and data and having it scalable, secure and
performing well is nice, but wouldn’t it be great if you could add
intelligent features to it?
Azure Search
Search is a common feature in most applications and yet it has traditionally been a difficult function to
implement. Azure Search provides a lot of the “plumbing” to do search. You spin up an Azure Search
instance, create an index that helps you search and fill it with data – that’s it. There are lots of options
that you can use to tweak Azure Search and there are lots of great features that will make searching
easier for your users:
Geo-search that gives users the ability to explore data based on how close a search result is
to a physical location.
Language analysers from Lucene as well as Microsoft‘s natural language processors (NLPs),
available in 56 languages to intelligently handle language-specific linguistics, including
verb tenses, gender, irregular plural nouns (for example, “mouse” versus “mice”), word
de-compounding, word-breaking (for languages with no spaces) and more.
Monitoring and reporting that tell you what was searched for and how fast and successful
the search was.
User experience features like sorting and paging search results and intelligent filtering,
and providing search suggestions.
Try it out Create your first Azure Search index in the portal.
Using the Face API, you can perform facial recognition and identification and can even determine
the colour of a person’s eyes, even if that person is wearing glasses.
The Language Understanding Intelligent Services API (or LUIS) can actually understand text,
based on the model you use to train it.
The Translator Speech API turns speech into text and translates it for you in real time
The Cognitive Services get their smarts through machine learning and artificial intelligence, which you
can train with your own datasets. These services are simply amazing and open up possibilities that we
couldn’t even dream of a mere few years ago.
Creating a bot is no trivial task. You need to keep track of the context of your interaction with the user
and you must be ready to respond to a multitude of possible interaction parameters. Bot Service helps
you with this in the following ways:
It helps you to keep track of the interaction context and provides you with templates to get
started from the Bot Framework.
It has tight integrations with Cognitive Services, making it easier to make your bot “smart.”
It helps you to integrate with services like Facebook, Slack, Microsoft Teams, Telegram and so on.
It offers all the benefits of a managed service in Azure: massive scale, built-in Continuous Delivery
(CD) and you pay only for what you use.
An example of a bot that you can build with Bot Service is one that provides your users with answers
to their most frequently asked questions. The interface of the bot can be a chat box that is on your
website.
Try it out Gets started with Azure Service Bus Queues and Topics.
With a queue, multiple applications write messages to the queue, but only one application at
a time can process a message.
With a topic, multiple applications write messages to the topic and multiple applications can
process a message at the same time.
Service Bus Topics work just like a queue and multiple applications can process the same message.
Applications can create a subscription to the topic that indicates what type of messages they are
interested in. Just like queues, topics have features like duplicate detection and a dead-letter
subqueue to which messages are moved when they fail to be processed correctly.
Event Hubs is designed for massive data ingestion. You can throw millions of messages per second at
it and it will handle that data for you effortlessly. It can retain messages for up to seven days or retain
them indefinitely by writing them to a data store using the Event Hubs Capture feature.
You can use Event Hubs to filter the data with queries, as it comes in and output it to a data store like
Azure Cosmos DB. You can even replay messages if you need to.
Try it out Get started sending messages to Azure Event Hubs in .NET Standard.
What makes IoT Hub unique is that in addition to receiving messages from devices, it can send
messages to them as well. It has the ability to manage your complete IoT infrastructure. You can use
IoT Hub to register devices and report their state, manage them by securing them and restarting them
and sending data to devices.
Try it out Connect your device to your IoT hub using .NET.
This is different from working with the Service Bus Queues and Topics, for which you’d need to poll
the Queue or Topics for new messages. Event Grid automatically pushes messages to subscribers,
making it a real-time, reactive event service.
Another important aspect of Event Grid is that it is serverless. This means that like Azure Logic
Apps and Azure Functions, Event Grid scales automatically and doesn’t need an instance of it being
deployed. You just configure and use it. And, you pay only when it is used, not for it just being there.
You want to be notified by email every time a user is added to or deleted from your mailing list in
MailChimp.
Azure Event Grid is used to activate an app in Azure Logic Apps and is configured to listen to changes
to the MailChimp mailing list. The next step is to send an email containing the name of the user that
has been added or deleted and the action that was performed (add or delete). Now, when a new user
is added to the mailing list, Event Grid signals the Logic App, which sends an email.
Try it out Monitor virtual machine changes with Azure Event Grid and Logic App.
Security today is one of the most important aspects of any application and
it is no simple thing to get right. Fortunately, Azure provides many services
to help you secure your application. We take a look at some of them in this
chapter.
Azure Active Directory provides all of these things and more out of the box. You store your user
identities in Azure Active Directory and have users authenticate against it, redirecting them to your
application only after they are authenticated. Azure Active Directory takes care of password
management, including common scenarios like “I forgot my password.”
Azure Active Directory is used by millions of applications every day, including the Azure portal,
Outlook.com and Office 365. Because of this, it is able to more readily detect malicious behaviour and
act on it. For instance, if a user were to sign in to an application from a location in Europe and then
one minute later sign in from Australia, Azure Active Directory would flag this as malicious behaviour
and ask the user for additional credentials through multifactor authentication.
These can be the credentials in a connectionstring that your application uses. Your application
would get the connectionstring from Key Vault instead of from the configuration system. This way,
administrators can control the secrets and developers never need to deal with them.
You also use Key Vault to store certificates like Secure Sockets Layer (SSL) certificates that you use to
secure the traffic to and from your applications over HTTPS.
Azure protects you from DDoS attacks with its Azure DDoS protection layer. This is a layer in the Azure
physical network that is not accessible to customers. This is part of the Azure platform and you get it
for free with all your services. You don’t need to do anything or configure anything to use it. It is
always there to protect you.
It can detect a malicious attack, as defined in the OWASP core rule set and block that attack from
reaching your application. It also reports on attempted or ongoing attacks, so that you can see which
threats are trying to get to your application. This provides an extra layer of security that protects your
applications.
By default, your data is encrypted when you store it in Azure SQL Database, Azure SQL Data
Warehouse, Azure Database for MySQL, Azure Database for PostgreSQL, Azure Storage, Azure
Cosmos DB or Azure Data Lake Store. And this all works automatically; you don’t need to do a thing
to configure it or to encrypt or decrypt data when you use it.
The Azure services that you choose to work with determine your
deployment options and vice versa. Therefore, it is important to
understand the deployment options that you have in Azure and
what their ramifications are.
Many of the Azure services that we’ve looked at so far in this book are able to have code
automatically delivered to them, often through a Continuous Delivery (CD) pipeline that you
set up within the service.
Besides the native capabilities of Azure services, you can use Visual Studio Team Services to build,
test and deploy your application. You can easily create new build and deployment pipelines in Visual
Studio Team Services as well as do things like automate load-testing and swap deployment slots into
production.
You can create Resource Manager templates in Visual Studio and Visual Studio Code using the Azure
Resource Group project template. You can also generate Resource Manager templates from the Azure
portal by clicking the Automation Script button, which is available on the menu bar of every resource
in the Azure portal. This generates the Resource Manager template for the given resource and even
generates code for creating the resource using the Azure command-line interface (CLI), Windows
PowerShell, .NET and Ruby.
After you have a Resource Manager Template, you can deploy it to Azure by using Windows
PowerShell, the Azure CLI or Visual Studio. Or, you can automate its deployment in a CD pipeline
using Visual Studio Team Services.
You use Resource Manager templates to deploy applications to run on the Azure platform, either in
the public cloud or on-premises, on Azure Stack.
A great example of deploying resources to the cloud using Resource Manager is the Deploy To Azure
button that you can find in many GitHub repositories, as illustrated in Figure 5-1.
Figure 5-1: One-button deployment of an Azure Logic App using an Resource Manager template in GitHub
You can use the Azure Service Fabric SDK to create applications for Service Fabric. You can also run
any executable in Service Fabric and you can even use it to host containers.
Service Fabric is amazing at making your applications just as well-performing, reliable and secure
as many Azure services, and you can use it anywhere: you can deploy Service Fabric in Azure,
on-premises, on your own computer and even on Virtual Machines (VMs) in other clouds.
After you have deployed your application in Azure Service Fabric, it provides you with benefits such
as these:
Load balancing
Automatic scaling
High availability
Self-healing
Rolling upgrades
Automatic rollback
Containers in Azure
Containers is one of those technology buzzwords that flies around the news. But, they are more than
just buzz – they are actually very useful for running your applications. A container is basically a light-
weight VM that starts and stops much faster than a VM and is therefore much more useful for
development, testing and running applications in production.
The major benefit that you derive from containers is that an individual container is always the same.
You run a container locally when you develop your app and you use the same container configuration
in the cloud or anywhere else. Your entire team uses the exact same container configuration, so you
know that the infrastructure is the same for everybody and in production. With containers, the age-
old developer’s fallback statement, “works on my machine,” now means that it will also work in
production.
There are many technologies for running containers and Docker is one of them. Azure can run and
manage containers for you with Azure Container Instances and Azure Container Service, and even
in Services Fabric and Azure App Service running on Linux.
Table 5-1 shows which service you can use for a given scenario when using containers.
Table 5-1: Choosing which Azure service to use for containers
Note Keep in mind that when you use containers, you are using an infrastructure as
a service (IaaS) product and that you are responsible for the operating system (OS),
patching, load balancing and so on.
Azure Stack
If you need your applications and data to remain on-premises, but you still want to benefit from the
power that Azure has to offer, Azure Stack is the product for you. Unique in the industry, Azure Stack
is an extension of Azure that you host in your own environment. Essentially, it is Azure-in-a-box.
You can run things like Azure App Service and Azure Virtual Machines on Azure Stack. Everything is
exactly the same as in the public cloud, only now you are running it on-premises. And if you decide
to move to the public cloud, you simply push services from Azure Stack to Azure.
IaaS PaaS
On-premises Azure Stack Azure Stack
Containers Service Fabric
Service Fabric
Public cloud Containers Service Fabric
Service Fabric Resource Manager templates
Now that you’ve know what Azure is and have learned about the services
that is has to offer, let’s begin using it.
You can use a preview of the Azure portal by visiting https://preview.portal.azure.com. The preview
already contains features that aren’t generally available yet that you can try out and provide feedback
on. The rest of this guide will focus on the generally available version of the portal, not the preview.
The first thing you’ll see in the Azure portal is a dashboard with tiles. You can create and customise
dashboards and share them with team members or keep them just for yourself.
You can also pin tiles (Figure 6-2) directly to your dashboards so that they are the first thing that you
see when you enter the portal. You can, for instance, pin tiles from all the service metrics that you care
about, to create a monitoring dashboard that you share with your team or display on a monitor in the
team room.
Finding services
Azure services are the central subject of the Azure portal. You can add and find them in several ways.
To create new services, in the upper-left corner of the portal window, click the plus sign (“+”).
This opens the search box for the marketplace, where you’ll find everything from Web App to
Linux Servers, as depicted in Figure 6-3.
When you’ve found the service that you want (Figure 6-4), a wizard takes you through configuring and
deploying it.
When you have some resources, you can find them through search. You can use the search box at the
top of the portal (Figure 6-5) to search through all of your resources and take you directly to them.
In the pane on the left side of the portal is the favourites menu. This menu displays the resource
categories (represented by their icons) such as Azure App Service. You can rearrange the icons by
dragging them up and down. You also can select which ones you want to see by expanding the
favourites menu and clicking the stars of those categories.
Understanding Blades
Pages in Azure are also called blades. Blades are everywhere and you can even pin them to your
dashboards. When you open a web app, you first see the overview blade. This particular blade
provides you with tools to stop, start and restart the web app and displays tiles showing its metrics,
such as number of requests and errors. When you choose another menu item, a new blade opens.
Blades always open in context. So, if you open the Deployment Slots blade and click the Create New
Deployment Slot button, a new blade shows up to the right of the Deployment Slots blade, preserving
the context you are in.
1. In the Azure portal, in the upper-left corner, click the Create A New Service button.
2. In the Search box, type Linux virtual machine.
You’ll get many search results, including Red Hat Enterprise Linux. Let’s try out its latest version.
b. Choose the drive type. SSD provides a faster VM, but is also more expensive. For this
walk-through, choose SSD.
c. Type a username.
d. Select Password for the Authentication type.
The performance of the VM determines how much you pay for it. There are many sizing options
for VMs, some small, some incredibly large. You can use the wizard to select how many cores
and how much memory you want and choose options based on that. Besides that, there are other
features that come with size options:
a. Type of hard drive (SSD or normal HDD).
b. The amount of max IOPS (Input/Output Operations Per Second). This determines the
performance of the VM in a significant way, especially if the applications that you run
read and write a lot from and to the hard drive.
e. The graphics card that is installed in the VM. This is useful if you need to do a lot of
graphics rendering or heavy computational workloads.
6. After you’ve selected the size, you can configure additional settings such as the Virtual Network
and IP address and installing extensions on the machine. For now, leave everything as is and
click OK.
7. Review the summary, agree to the terms and then click Purchase.
The VM will now be deployed. This usually takes just a few minutes.
Cloud Shell is the Azure CLI in the browser – there is no longer a need for you to install anything on
your PC. Cloud Shell uses the Azure CLI version 2.0. You can use Bash or PowerShell in the Cloud Shell
to interact with your Azure resources.
To connect to the VM, you need its IP address. Find the VM in the Azure portal (either by searching
for it or navigating to it). In the Overview blade of the VM, in the upper-left corner, click the connect
button (see Figure 6-6). When you click it, the blade displays the IP address that can be used to
connect with the VM, as shown in Figure 6-6. Copy the IP address.
Now, you can use this command directly in the Cloud Shell: just paste it and press Enter. You will
see a warning that there is no authentication key. This is because we chose to work with a password,
instead. Choose Yes, type your password and you are in! Now you are connected to Red Hat Linux
enterprise and you can begin using it. Figure 6-7 shows that we are logged in to the Virtual Machine
through Cloud Shell and traversing the file system:
Figure 6-7: Traversing the Linux file system using the Cloud Shell in the Azure portal
1. Go to the VM, select the Disks tab and then click Add Data Disk, as shown in Figure 6-8.
2. The Create Managed Disk Wizard opens. Use this wizard to create a managed drive (instead of an
unmanaged drive).
Managed disks are completely managed by Azure; you don’t need to create and maintain an
underlying storage account for them. Optionally, you can choose the size of the drive and what
should be on it, but we are going to leave everything as is. Type a name and then click Create.
You now have an additional drive attached to your VM.
You can also create and attach a new drive via the Cloud Shell or Azure CLI by using this
command:
az vm disk attach -g myResourceGroup --vm-name myVM --disk myDataDisk --new --size-gb 50
If you need help with the Azure CLI, you can type az -h. All Azure CLI commands follow the same
structure: az noun(s) (e.g. vm) verb (e.g. attach) options.
After you’ve created a new drive for your VM, you need to initialise it in Linux. This document guides
you through the process.
Creating additional drives for extra VM storage is simple. The steps after that can be more
complicated, depending on the OS that you use.
To follow along you’ll need to have the Azure CLI (v2.0 or higher), Git (v2 or higher), Node.js and NPM
(v6 or higher) and MongoDB (3.4 or higher) installed on your computer.
We’ll use a sample application that uses the MEAN.js web framework.
Creating the web app and database using the Azure portal
To host the Node.js application, we’ll create a new web app in Azure Web App.
2. Search for Web App. The Web App blade opens. Click Create to get started.
3. The Web App Create blade opens.
You can run as many App Services on an App Service Plan as you want, as long as you realise that
you need to share the resources amongst all of the App Services.
d. Choose the location. Preferably, a location that is the same as or close to where the
web app is.
e. Click Create.
1. Open a command prompt on your computer and navigate to the bin directory of your MongoDB
installation. This could be something like C:\Program Files\MongoDB\Server\3.4\bin.
2. Type mongo to connect to the local MongoDB server.
3. If it fails, make sure that your MongoDB database is started. Often, you need to start it by running
mongod.
4. In the command window, navigate to a directory to which you want the application source to be
downloaded.
7. When it is fully loaded, you’ll see a message that contains the application URL. Open a browser
and navigate to the server address (something like http://localhost:3000). This should look similar
to Figure 6-10.
We are going to use the Azure CLI to push the application from Git to Azure. Make sure that you
have the Azure CLI 2.0 or newer installed on your computer. When that is done, you need to run the
following az login command to log in to your azure subscription. This opens a website where you
can authenticate and authorise the usage of your Azure subscription by the CLI.
For FTP and local Git, you must have a deployment user configured on the server to authenticate your
deployment. This deployment user is account-level and is different from your Azure subscription
account. You need to configure this deployment user only once. In the Azure CLI, run the following
command, where username and password are values that you make up and fill in (do not include
the < or > character):
az webapp deployment user set --user-name <username> --password <password>
Next, we associate the local Git repository with the web app by running the following:
az webapp deployment source config-local-git --name <app_name> --resource-group
<resource_group_name>
We will now use this URL to push the application to Azure. First, we add an Azure remote to the local
Git repository. cd to the meanjs directory of the application source code. Now run:
git remote add azure <url_for_deployment>
To deploy the app, run git push azure master. This prompts you for the credentials that you
created earlier. The deployment can take a while. It will notify you when it’s done.
After it’s done, you can browse to the application using http://<app_name>.azurewebsites.net.
Now, the application is deployed to the web app and we have a Cosmos DB database running with
the MongoDB API, but the two aren’t connected yet. Let’s do that next.
You can find the Cosmo DB connection string that you need to use for the MONGODB_URI value in the
Azure portal. There, you can find it in the Connection String menu of the Cosmos DB account.
After running the command with the Azure CLI, the Application Settings of the web app will look like
Figure 6-11.
Instead of running the Azure CLI command, you could’ve also added the setting using the Azure
portal.
Now, navigate to the web app again using http://<app_name>.azurewebsites.net. Try signing up
a new user. When that succeeds, the application is communicating with the database. Now you have
a Node.js application with an Azure Cosmos DB using the MongoDB API.
We are going to use GitHub to push our code to and link that to our web app so that changes are
deployed automatically in a Continuous Delivery (CD) pipeline.
b. Leave the other settings as they are (public repository, don’t create a README)
c. Create the repository. This results in a screen that should look similar to Figure 6-12
3. Use the URL to set a remote destination for the local Git repository. You can do that in the
command window.
Now, our code is in GitHub and you can share it with your team. Next, let’s set up CD. We’ll use
the Deployment Options feature of Web App through the Azure portal. We could’ve also used the
Continuous Delivery feature in Web App, but that requires a Visual Studio Team Services account
and we want to keep it simple.
1. In the Azure portal, go to the web app that hosts the Node.js application.
3. It’s possible that this is already configured for the local Git Repository. If this is the case, you need
to click Disconnect.
5. In the Authorisation section, authorise Azure to use GitHub by clicking Authorise and granting
permission.
6. In the Choose Project section, choose the GitHub repository that you just created.
7. Leave the Branch set to master
Go back to the Deployment Options menu. You can now see that it is connected. From this point,
whenever you push a new version of source code to GitHub, it will be built and deployed to the web
app automatically, as demonstrated in Figure 6-13. You can also force this process by clicking the
Sync button.
You can have deployment slots for staging, load-testing and production (which is always the original
App Service, so the Node.js web app in our case). In fact, you can have as many deployment slots as
you want, without incurring any additional costs. The deployment slots all run in the same App Service
Plan and that’s what you pay for. You should keep in mind that having additional deployment slots in
an App Service Plan will consume resources like CPU and memory.
You can create new deployment slots from the Deployment Slots menu item in the web app. Make
sure that you are running the web app in the Standard or Premium pricing tier because the free plan
doesn‘t come with any Deployment Slots.
Additionally, you can test your final version in a deployment slot and when you're happy, you swap it
with the production slot. This warms-up the application before it swaps, which results in a deployment
with no downtime.
Let’s go through creating a deployment slot and swapping to it.
1. In the Azure portal, go to the web app that hosts the Node.js application.
2. On the menu bar, click Deployment Slots. The deployment slots blade opens.
3. Click the plus sign (+) to create a new deployment slot.
b. Choose the Node.js web app as the Configuration Source (this copies the application
settings to the new slot).
c. Click OK to create the slot.
a. Set up CD for the slot just as you did in the previous procedure for the web app.
b. Disconnect the CD connection in the original Node.js web app. This way, when you push
new code, it’s delivered only into the staging slot
a. Change some text in the home.client.view.html file (you can find it in the
meanjs\modules\core\client\views folder).
b. Commit it to Git and Push it to GitHub, the same as when you deployed the Node.js app.
The new version is now in the staging slot and not in the original web app (which we call the
production slot). You can verify this by navigating to the URL of the Node.js web app and to the URL
of the staging slot (which you can find in the overview blade of the slot, just like in the web app
overview blade).
2. On the menu bar, click Deployment Slots to open the deployment slots blade.
After the swap is complete, the new version of the Node.js web app is in production (test it by
navigating to the URL of the Node.js web app). Using deployment slots in this way is very beneficial
because you can test the new version before it goes into production and then deploy it to production
with no downtime.
You’ll see some logging when you use the application in the web app to generate some traffic.
You can set up Application Insights in the Azure portal from the web app.
1. Go to the Azure portal and then to the web app that hosts the Node.js application.
2. On the menu bar, click Application Insights.
a. Type a name and select a location for the Application Insights instance.
b. Click OK. Now, Application Insights will be deployed and starts to collect data for the
application.
You do need to configure your application to begin sending data to Application Insights. For our
sample Node.js application, you need to do the following:
3. Go to the Azure portal and retrieve the Application Insights instrumentation key.
5. Add the following three lines of JavaScript code before the line:
var app = require('./config/lib/app');
const appInsights = require("applicationinsights");
appInsights.setup("<instrumentation_key>");
appInsights.start();
6. Push the changes to GitHub and start the automatic deployment. From the command prompt,
run the following:
git commit -a -m “added Application Insights support”
7. Run git push github and the changes will be pushed to GitHub and automatically deployed to
the web app.
When the deployment is finished, the application will send data to Application Insights.
By default, Application Insights performs smart detection. This is a very clever feature that detects
when things are going wrong and alerts you when they do. It can detect things like a sudden increase
in failed requests and when the application is behaving unusually slowly. You can also create your own
Now, go to the Azure portal and find the Application Insights resource and click it. When you’re there,
you will see the overview, which shows you basic metrics such as the server response time, the page
view load time and the number of server requests and failed requests. If you see some data there,
Application Insights is working.
The web app has a menu item called Scale Out, as shown in Figure 6-15. You can use this to scale out
manually or automatically.
Scaling out means that you add more instances of your application to handle the load. When you
scale out or scale in automatically, you can do that based on metrics, such as percentage of use of
CPU or memory, on a schedule (every day at 5 PM) or a mix of both. This is very easy to set up and
monitor.
Serving traffic to your web app over Secure Sockets Layer (SSL) is possible by importing an SSL
certificate into the web app and binding it to one of your (custom) domain names. You can either
import your own SSL certificate that you or your company bought, or buy a new one through
Azure App Service Certificates, which makes it easy to buy and validate the certificate. After importing
the certificate, you couple it to one of the domain name bindings of your web app. You can do all of
this from the SSL Certificates menu in the web app.
A backend that provides APIs to communicate with a database and do things like authentication,
offline synchronisation and push notifications
You can build the backend for the Mobile App application in Node.js and C#. The client SDK is
available for basically every mobile platform that is in use. For cross-platform, native and hybrid
mobile apps. It is available for Android, Cordova, iOS, Windows, Xamarin.Android, Xamarin.Forms
and Xamarin.IOS.
In this walk-through, we create a new Mobile App backend with C# that we use with an Android app,
which we build with Xamarin.Android.
To follow along, you need to install the Mobile Development with .NET workload using the
Visual Studio 2017 installer. This installs the Xamarin for Android tools and the necessary SDKs.
You can do the same when you are working on a Mac in Visual Studio for Mac.
1. In the Azure portal, click Create A New Service and then, in the Search box, type Mobile App
Quickstart.
2. Select the Mobile App Quickstart result and then click Create.
The Mobile App Create Wizard opens.
After the Mobile App is deployed, you can begin using it. In the Azure portal, in the mobile app,
click the Quickstart menu item and then select Xamarin.Android. The Quickstart Wizard opens.
1. In the Step 2 area, select C# and then click Download. This downloads the backend project that
you are going to deploy to the mobile app.
2. Unzip the file that you just downloaded and then open it with Visual Studio 2017 or Visual Studio
for Mac.
3. In Visual Studio, right-click the project file and then select Publish.
4. Select App Service and then select Existing and click Publish.
5. Find your mobile app and then click OK to begin publishing. That’s it! The mobile backend is up
and running.
Run the application by pressing F5. This starts the Android Emulator and deploys the client app. The
client app is a todo application. You can add an item in the textbox and it will be written to the
backend of your mobile app.
1. Go to your mobile app backend project in Visual Studio 2017 or Visual Studio for Mac.
4. Right-click the project file and then publish it to your mobile app.
success = true;
}
catch (Exception ex)
{
CreateAndShowDialog(ex, "Authentication failed");
}
return success;
}
[Java.Interop.Export()]
public async void LoginUser(View view)
{
// Load data only after authentication succeeds.
if (await Authenticate())
{
//Hide the button after authentication succeeds.
FindViewById<Button>(Resource.Id.buttonLoginUser).Visibility = ViewStates.Gone;
This creates a new method to authenticate a user and a method handler for a new Sign In button.
3. In the OnCreate method, delete or comment-out the following line of code:
OnRefreshItemsSelected();
4. In the Activity_To_Do.axml file, add the following LoginUser button definition before the existing
AddItem button:
<Button
android:id="@+id/buttonLoginUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="LoginUser"
android:text="@string/login_button_text" />
A Sign In button now appears next to the Add button. You won’t be able to add any items without
signing in because all the actions on the TodoItemController are now secure. When you click Sign
In, you are directed to the Azure Active Directory authentication screen. Here, use the account that
you use to sign in to the Azure portal. This one is added to the Azure Active Directory by default. Sign
in and you’ll see that you are successfully logged in, as depicted in Figure 6-16, and can begin adding
todo items.
1. In Visual Studio 2017 or Visual Studio for Mac, go to the Xamarin Android client app.
Now, the app is working exactly the same as before, but with a few changes. It uses a
IMobileServiceSyncTable instead of a IMobileServiceTable object. It also uses the SQLite
NuGet package. This initiates a SQLite database on the Android device that the app uses to save data
when it is not online. When access to the internet is restored, changes from the local SQLite database
are pushed to your mobile app and potential changes that happened on the backend are
synchronised to the app on the Android device. Let’s try that out:
1. Have the app running on the Android emulator.
4. Disconnect from the internet. In the Android emulator, you can do that in the Extended Controls,
by setting the Signal Strength of the Network to None.
5. Add another item and complete an item by checking it. The app continues to work on the local
SQLite database.
You can verify that the items aren’t written to the backend database by connecting to the Azure
SQL Database that we’ve created earlier using a tool like SQL Server Management Studio. You can
find the connectionstring for the Azure SQL Database when you navigate to it in the Azure
portal.
6. Connect the Android device to the internet again. In the Android emulator, go to the extended
controls and then set the Signal Strength to Great.
7. In your mobile app, click the Refresh button. The local changes will now be synced to the Azure
Mobile App.
Check the Azure SQL Database to see the changes that are now synchronised to the backend.
Because the mobile app is an Azure App service, it has all the same features that the other App
Services have. This means that mobile app can also scale automatically, that you can have the same
monitoring and alerting and that you can do additional diagnostics with streaming logs and even
incorporate application debugging.
When you move the app to production, you can provide additional security using App Service
Certificates. You can also set up CD, just like we did for the Node.js application. And you can use
deployment slots to deploy with no downtime.
Setting up all of this used to be difficult; now these problems are solved. Let Azure to do the heavy
lifting for you, so that you can focus on building things that matter!
The Azure ecosystem not only helps you to more quickly and effectively
create dynamic applications, but with the Azure Marketplace, you can find
solutions of all sorts to assist your development efforts. And then it can
help you to connect your product to users all over the globe.
The advantage of the Marketplace is the ease of use. Solutions are deployed ready-to-run, along with
all of the required bits and pieces. Sometimes, this is a Virtual Machine with software installed, a
Virtual Network configured and an integrated licence installed or a licence that you bring yourself.
Sometimes, this is a service that you acquire, like a subscription to the Bing Maps API for Enterprise.
You can use the Marketplace to easily test-drive new software and for using enterprise-grade
solutions. No matter what you need, you can probably find a solution for it in the Marketplace.
Azure Solutions
You can learn from companies using Azure successfully, through Azure Solutions. These show you
product documentation, case studies and architecture best practices for common Azure use cases
like Digital Marketing, SharePoint on Azure, Line-of-Business applications and Mobile applications.
You’ve seen that no matter what programming language you use or what platform you write
applications for, Azure can help you, with services for almost every scenario.
We hope that you continue to use this eBook to become better acquainted with the vast range of
Azure services and determine which ones best fit your scenario.
The days of having to write complicated “plumbing” yourself are over; you can now take advantage
of a wealth of prebuilt solutions. Free yourself up to work on the things that matter and let Azure take
care of the solved problems.
Free access to our most popular products for 12 months, including compute, storage,
networking and database
Michael Crump works at Microsoft on the Azure platform and is a coder, blogger
and international speaker on various cloud development topics. He’s passionate
about helping developers understand the benefits of the cloud in a no-nonsense
way.
You can reach Barry on Twitter @AzureBarry and through his website at
https://www.azurebarry.com/.