Virtual Machines in Azure
A complete, plain-English guide to Azure Virtual Machines: how they are built, how they are sized, networked, secured, scaled, monitored, protected and paid for, and how to avoid the mistakes that cost teams money and sleep.
Imagine you want to open a bakery, but you do not want to buy a building, pour concrete, wire the electricity and hire a security guard before you bake a single loaf. Instead, you walk into a huge commercial kitchen complex, point at a ready-made kitchen of the size you need, and start baking within minutes. When you are done, you hand back the keys and stop paying. An Azure Virtual Machine is exactly that kitchen: a complete computer that you rent from Microsoft, shaped to your needs, available in minutes, and billed only while you use it.
This guide assumes you know nothing about the topic. Every new word is explained when it first appears, with a comparison to everyday life. By the end you will understand what happens behind the scenes when a virtual machine is created, how to choose the right size and storage, how to keep it safe and available, how to watch it, and how to run it economically in production.
1What Is a Virtual Machine, Really?
Before Azure, we need to understand the simple idea underneath it: one real computer pretending to be many.
The physical computer problem
A physical server is a powerful computer with processors, memory, disks and network cards, housed in a data centre. In the old days, a company bought one server for each application. The payroll system had its own server, the email system had another, and the website had a third. Most of these machines sat idle for most of the day, using perhaps ten or fifteen percent of their power. The company still paid for the electricity, the cooling, the space and the maintenance of the unused ninety percent.
Virtualization solved this waste. It is a technique where special software slices one physical machine into several independent, software-defined computers. Each slice behaves exactly like a real computer, with its own operating system, its own files and its own settings, yet none of them can see or disturb the others.
Think of a big apartment building. The building is the physical server. Each apartment is a virtual machine. Residents share the plumbing and the electricity supply, but each family has its own locked door, its own furniture and its own privacy. If one family makes a mess, the neighbours are not affected.
What makes a machine “virtual”
A virtual machine, often shortened to VM, is a software copy of a computer. It has virtual processors, virtual memory, virtual disks and virtual network cards. These are not physical parts. They are portions of the real hardware that the controlling software hands out on demand. The operating system inside the VM, such as Windows Server or Linux, believes it is running on a real computer and has no idea it is sharing hardware.
The controlling software is called a hypervisor. It sits between the physical hardware and the virtual machines, deciding who gets how much processing time, memory and network capacity. It also enforces isolation, which means making sure one VM can never read another VM’s memory or files.
Infrastructure as a Service, or IaaS, means renting basic computing building blocks such as machines, storage and networks from a provider. Azure Virtual Machines are the best-known IaaS offering. You control the operating system and everything above it, and Microsoft controls the physical hardware and the building.
Why this matters for you
Because a VM is only software, it can be created, copied, resized, paused and deleted in minutes. You no longer wait weeks for hardware to be ordered and delivered. You can try an idea on Monday, decide it was wrong on Tuesday and delete the whole thing without having wasted a single purchase order. This speed and flexibility is the heart of cloud computing.
2Azure Virtual Machines in Context
Azure offers many ways to run software. Knowing where VMs fit saves you from choosing the wrong tool.
Microsoft Azure in one paragraph
Microsoft Azure is a collection of services that Microsoft runs in its own data centres around the world, which you rent over the internet. These services include computing, storage, databases, networking, analytics and artificial intelligence. A virtual machine is one of the oldest and most flexible of those services, and many other Azure services quietly use VMs underneath.
The compute spectrum
Azure offers a ladder of compute choices. At the bottom, you manage the most yourself; at the top, Azure manages almost everything. Choosing the right rung is one of the most important architecture decisions you will make.
| Option | What You Manage | What Azure Manages | Best For |
|---|---|---|---|
| Virtual Machines | Operating system, patches, software, scaling rules, security settings | Physical hardware, hypervisor, data centre | Full control, legacy applications, special software |
| Virtual Machine Scale Sets | Image, scaling rules, application | Creation and removal of identical VMs | Fleets of identical machines that grow and shrink |
| Container services | Application packaged in a container | Servers, orchestration in managed modes | Microservices, portable applications |
| App Service | Application code and settings | Operating system, runtime, patching, scaling | Websites and APIs |
| Functions | Small pieces of code | Everything else, including scaling to zero | Event-driven tasks, glue logic |
Getting to work can mean buying a car (a VM: total control, total responsibility), leasing a car with maintenance included (a managed platform), taking a taxi (functions: pay per ride) or riding a bus (shared, fixed routes). Each is right in some situation and wrong in another.
When a VM is the right answer
Choose virtual machines when you need control over the operating system, when the software cannot run on a managed platform, when you are moving an existing application to the cloud with minimal change, when licensing demands a specific server, or when you need special hardware such as graphics processors. This approach is often called lift and shift, meaning you move the application as it is without redesigning it.
Many beginners assume a VM is always the safest default. It gives the most control, but it also gives the most work: patching, hardening, monitoring and backup are all your job. If a managed service can do the same task, it usually costs less in human effort.
3Core Building Blocks of an Azure VM
A VM is never alone. It is a small family of connected resources that must be understood together.
When you create a virtual machine in Azure, you actually create several separate resources that cooperate. Each one has its own life, its own settings and its own cost. Understanding this family prevents surprises, especially when you delete a VM and discover that some parts remain and keep billing.
Subscription and Resource Group
A subscription is your billing and access boundary. A resource group is a folder that holds related resources so they can be managed and deleted together.
Virtual Machine
The compute object itself: it defines the size, the image, the administrator settings and the links to disks and network cards.
Managed Disks
Virtual hard drives, one for the operating system and optionally more for data, stored durably by Azure.
Network Interface
The virtual network card that connects the VM to a virtual network and carries its private address.
Virtual Network and Subnet
Your private network in the cloud, divided into smaller sections called subnets.
Network Security Group
A set of allow and deny rules that act like a doorman for network traffic.
Public IP Address
An optional internet-facing address. Many secure designs deliberately avoid it.
How they connect
The VM points to its disks and to one or more network interfaces. Each network interface sits inside a subnet of a virtual network, may be protected by a network security group, and may optionally hold a public address. The resource group simply holds them all together for convenience.
flowchart TD
SUB[Subscription] --> RG[Resource Group]
RG --> VM[Virtual Machine]
RG --> VNET[Virtual Network]
VM --> OSD[OS Disk]
VM --> DD[Data Disks]
VM --> NIC[Network Interface]
NIC --> SN[Subnet]
VNET --> SN
NIC --> NSG[Network Security Group]
NIC --> PIP[Public IP optional]
Deleting only the VM object often leaves its disks, network card and public address behind. They keep costing money while doing nothing. Deleting the whole resource group, or choosing to remove associated resources during deletion, avoids these orphaned leftovers.
4How Azure Runs a VM Behind the Scenes
Understanding the hidden machinery explains many behaviours that otherwise seem mysterious.
Hosts, hypervisor and fabric
Azure’s data centres contain enormous numbers of physical servers called hosts. Each host runs a hypervisor derived from Microsoft’s Hyper-V technology, customised heavily for cloud use. Above the hosts sits a management layer often called the fabric controller. Think of it as the building manager who knows which apartments are empty, which are occupied, which pipes need repair and where each new tenant should move in.
When you ask for a new VM, your request travels to Azure’s control plane, the part of the system that accepts instructions and makes decisions. The control plane checks your permissions and your quota, which is your allowed limit of cores in a region. It then asks the placement system to find a host with enough free capacity of the right hardware type. The chosen host creates the VM, attaches the disk and network card, and starts it.
Control plane and data plane
These two terms appear everywhere in cloud work. The control plane is where you manage resources: create, resize, start, stop and delete. The data plane is where the actual work flows: your application’s traffic, your disk reads and your database queries. Separating them means a problem in the management interface does not necessarily interrupt running workloads.
In an airport, the control tower decides which planes take off and land, while the runway carries the actual planes. The tower is the control plane and the runway is the data plane. If the tower’s display screens flicker, planes already in the air keep flying.
The life of a creation request
Request arrives
You submit your request through the portal, a command-line tool or an automation template. All of these talk to the same management service.
Identity and policy check
Azure confirms who you are, whether your role allows this action, and whether any organisational policy forbids it, such as limiting regions or sizes.
Quota and capacity
Your cores are compared with your regional limit, and the placement system searches for a host with free room of the requested type.
Resources are assembled
The disk is created from the chosen image, the network interface is attached, and the VM definition is written down.
Boot and agent start
The VM boots. A small helper program, the VM agent, starts inside it and reports readiness back to Azure.
Sometimes a creation fails with a capacity message even though you have quota. Quota is your permission to use resources; capacity is whether the physical room exists right now in that place. Trying another size, zone or region usually resolves it.
5Regions, Availability Zones and Where Your VM Lives
Location decides speed, legal compliance, resilience and sometimes price.
Regions
A region is a geographic area containing one or more data centres, such as Central India, West Europe or East US. When you create a VM you must choose a region. Everything related to that VM, including its disks, usually lives in the same region. Choosing a region close to your users reduces latency, which is the delay before data starts to arrive. Distance matters because data cannot travel faster than light through cables.
Region choice also has legal consequences. Some laws require that certain data stay inside a country or a bloc. Prices differ slightly between regions, and not every VM size or feature exists everywhere, particularly the newest hardware.
Availability Zones
Many regions are divided into availability zones. A zone is one or more data centres with independent power, cooling and networking, located a short distance apart inside the same region. Where zones are offered, there are normally three. If a fire, flood or power failure knocks out one zone, the others keep working.
A region is a city. Zones are three separate neighbourhoods in that city, each with its own power substation and water supply. Keeping copies of your shop in all three neighbourhoods means a power cut in one will not close your business.
Region pairs and disaster recovery
Many regions are paired with a second region in the same geography, hundreds of kilometres away. Pairing helps Azure schedule planned maintenance so both regions are not updated at once, and it simplifies planning for the rare disaster that affects an entire region. Today, availability zones protect you from a single data centre failure, while a second region protects you from a regional disaster.
graph TD
GEO[Geography] --> R1[Region A]
GEO --> R2[Paired Region B]
R1 --> Z1[Zone 1]
R1 --> Z2[Zone 2]
R1 --> Z3[Zone 3]
Z1 --> V1[VM copy 1]
Z2 --> V2[VM copy 2]
Z3 --> V3[VM copy 3]
Placing a single VM in a single zone and calling the design highly available. One VM in one zone is exactly one point of failure, however powerful the machine.
6VM Sizes and Families: Choosing the Right Machine
A size is a bundle of processors, memory, disk performance and network capacity at a fixed hourly price.
How to read a size name
Azure sizes have names such as Standard D4s v5. The letter identifies the family, which describes the purpose. The number is the count of virtual CPUs, often called vCPUs. Lowercase letters add features, for example a letter that signals premium storage support, and the version number shows the hardware generation. Newer generations usually give better performance for the same or lower price, so avoiding old versions is wise.
The main families
Balanced CPU and Memory
Good starting point for web servers, small databases, development and test machines, and most business applications.
More CPU per Memory
For busy web servers, batch jobs, gaming servers and anything that mostly burns processor time.
More Memory per CPU
For large databases, in-memory caches and analytics that keep huge datasets in RAM.
Very Fast Local Disks
For databases and big-data engines that read and write enormous amounts of data per second.
Graphics Processors
For machine learning training, rendering, video processing and scientific simulations.
Clusters and Fast Interconnects
For weather modelling, engineering simulation and other tightly coupled calculations.
Earn Credits, Spend in Spikes
For machines that are mostly quiet with occasional busy periods, at a lower base price.
Burstable machines explained
A burstable size runs at a modest baseline of processor power and earns credits while it is quiet. When work arrives, it spends the saved credits to go faster for a while. This is like a phone data plan with rollover: you save during quiet months and spend during busy ones. If credits run out, the machine slows to its baseline, which surprises teams that place steady heavy workloads on burstable sizes.
Processor architectures
Azure offers machines with Intel and AMD processors, and also with Arm-based processors that can deliver strong performance per unit of cost for compatible software. Software must be built for the processor type, so an application compiled only for the traditional architecture will not run on Arm without being rebuilt.
Start with a size slightly smaller than your guess, measure real usage for a couple of weeks, and then adjust. Resizing is easy; refunds for overbuying are not. Look at average and peak processor use, memory pressure and disk waiting time before deciding.
Choosing a size by vCPU count alone. Each size also caps disk operations per second, disk throughput and network bandwidth. A machine with plenty of processors can still be starved if its disk limits are too low for the workload.
7Images and Operating Systems
An image is the frozen starting point from which every new VM is born.
What an image is
An image is a template of a disk that already contains an operating system and sometimes pre-installed software. Creating a VM from an image is like photocopying a fully written form: you get a fresh, ready-to-use copy each time. Azure offers a large catalogue called the Marketplace with images from Microsoft and many other vendors, including various Windows Server versions and numerous Linux distributions.
Where images come from
Marketplace images
Published by Microsoft and partners, regularly refreshed with security updates. Some include licences for commercial software, which adds to the hourly cost.
Custom images
Created from a VM you have prepared with your own software and settings. Useful when every new machine must start identical to a tested baseline.
Shared image galleries
A managed library that stores versions of your custom images, replicates them across regions and shares them across teams and subscriptions with controlled access.
Golden images and image pipelines
Mature organisations build what they call golden images: carefully hardened, patched and tested templates. Rather than patching hundreds of running machines one by one, they produce a new golden image version regularly and replace old machines with fresh ones. This approach, sometimes called immutable infrastructure, means machines are never repaired in place; they are replaced. It reduces drift, which is the slow, unplanned divergence of machines that were supposed to be identical.
A restaurant chain does not let each branch invent its own recipe. A central kitchen creates the approved recipe, and every branch follows it. If the recipe improves, all branches get the new version rather than each improvising changes.
Generation 1 and Generation 2
Azure VMs come in two hardware generations that describe how the virtual computer starts up and what features it supports. Generation 2 machines use a modern startup method that supports larger disks, faster boot and security features such as Secure Boot and virtual trusted platform modules. Unless an old operating system forces otherwise, Generation 2 is the better choice.
Licensing considerations
Windows Server and some other software require licences. Azure can include the licence in the hourly price, or you can bring your own existing licences if your agreement with Microsoft allows it, a benefit known as Azure Hybrid Benefit. We discuss the savings in the pricing chapter.
8Storage and Disks for Virtual Machines
Storage decides how fast your applications feel and whether your data survives failures.
The three kinds of storage on a VM
OS Disk
Holds the operating system. Created from the image, persistent, and attached for the life of the VM.
Data Disks
Optional extra persistent disks for application data, kept separate so they can be resized, moved or protected on their own.
Temporary Disk
A fast disk on the physical host for scratch files. Its contents can disappear when the VM moves to another host, so never keep anything precious on it.
Managed disks
In the past you had to manage storage accounts yourself to hold virtual hard drive files. Today, managed disks remove that burden: you simply choose a type and a size, and Azure handles placement and durability. Behind the scenes, data is stored with multiple copies so a hardware failure does not lose it.
Disk types
| Type | Character | Typical Use |
|---|---|---|
| Standard HDD | Lowest cost, slower, based on spinning disks | Backups, rarely used data, non-critical development |
| Standard SSD | Consistent, moderate performance | Web servers, light applications, test environments |
| Premium SSD | Low delay, high performance for production | Databases, busy business applications |
| Premium SSD v2 | Performance and capacity set independently of each other | Demanding databases where tuning cost precisely matters |
| Ultra Disk | Highest performance and lowest delay, adjustable live | The most intense transactional workloads |
Caching
Disk caching keeps recently used data on the host for faster reading. Operating system disks usually benefit from read and write caching. Data disks holding databases often use read-only caching or none, depending on the workload, because write caching can put recent writes at risk if the host fails at the wrong moment. The correct choice depends on what the software promises about data safety.
Protecting data on disks
Azure encrypts managed disks at rest by default using keys it manages. You may choose to control the keys yourself using a key vault, which gives you the power to rotate or revoke them. Encryption at the host extends protection to temporary disks and caches. Snapshots capture a disk at a moment in time, like a photograph, and are useful before risky changes.
The OS disk is the shelf where your computer’s brain keeps its instructions. Data disks are filing cabinets you can unplug and carry to another room. The temporary disk is a whiteboard: handy for quick notes, but wiped whenever the cleaners come.
Storing application data or swap files that matter on the temporary disk. When the VM is redeployed or moved, that data is gone with no way to recover it.
9Networking for Virtual Machines
A VM that cannot be reached is useless, and a VM that can be reached by everyone is dangerous. Networking finds the balance.
Virtual networks and subnets
A virtual network, or VNet, is your private, isolated network inside Azure. You choose its address range, which is a block of private numbers from which addresses are handed out. You divide it into subnets, which are smaller sections, usually one for each role such as web, application and database. Machines in the same virtual network can talk to each other privately by default.
Private and public addresses
Every network interface receives a private address inside its subnet. A public address is optional and makes a machine reachable directly from the internet. Good designs give public addresses only to carefully chosen entry points, such as load balancers or gateways, and keep the application and database machines private.
Network security groups
A network security group, or NSG, holds a list of rules. Each rule says to allow or deny traffic based on source, destination, port and protocol, and each has a priority number; the lowest number is checked first. NSGs can be attached to subnets or to individual network interfaces. They work like a doorman checking a guest list: the first matching rule decides.
flowchart LR
U[Internet User] --> LB[Load Balancer]
LB --> W[Web Subnet VMs]
W --> A[App Subnet VMs]
A --> D[Database Subnet VMs]
N1[NSG Web rules] -.protects.-> W
N2[NSG App rules] -.protects.-> A
N3[NSG Data rules] -.protects.-> D
Reaching VMs safely
Administrators need to log in to machines, traditionally over remote desktop for Windows or secure shell for Linux. Opening those management ports to the whole internet invites constant automated attacks. Safer options include Azure Bastion, a managed service that gives browser-based access without exposing public addresses, private connections through a VPN or ExpressRoute link, and just-in-time access that opens a management port only for a short approved window.
Connecting networks
VNet peering
Links two virtual networks so their machines communicate privately over Microsoft’s backbone with low delay, even across regions.
VPN Gateway
An encrypted tunnel across the public internet between Azure and an office or another cloud.
ExpressRoute
A private dedicated circuit between your premises and Azure that does not travel over the public internet, offering predictable performance.
Distributing traffic
Load balancers spread incoming requests across several VMs so no single machine is overwhelmed and failed machines are skipped. Azure offers options that work at different layers: some route raw network connections very fast, others understand web requests and can route by address path or terminate secure connections, and global options steer users to the closest healthy region.
Accelerated networking
Normally, network traffic passes through the host’s virtual switch software, which adds small delays. Accelerated networking lets traffic bypass much of that software path using specialised hardware, lowering delay and processor use. Most modern sizes support it and it is generally worth turning on.
Plan address ranges before you build. Two networks with overlapping ranges cannot be peered or connected through gateways, and changing ranges later is painful.
10High Availability: Availability Sets, Zones and Maintenance
Hardware fails and updates are inevitable. A resilient design assumes both and plans for them.
Why machines go down
There are two kinds of interruption. Unplanned events include hardware failure, a power fault or a network problem on the host. Planned events are maintenance activities where Azure updates the host software or firmware. Azure tries to make planned maintenance invisible using techniques such as memory-preserving updates, which freeze a VM for a few seconds without rebooting it, and live migration, which moves a running VM to another host. Some maintenance still requires a restart, and failures can never be reduced to zero.
Fault domains and update domains
A fault domain is a group of hardware sharing a common power source and network switch, like a single electrical circuit in a house. An update domain is a group that can be updated and rebooted together. Spreading machines across several of each means one failure or one update wave never takes all your machines down together.
Ways to spread your machines
| Mechanism | Protects Against | Notes |
|---|---|---|
| Single VM with premium disks | Very little; a basic agreement applies | Acceptable for development, risky for production |
| Availability set | Rack-level failures and update waves inside one data centre | Older approach; spreads across fault and update domains |
| Availability zones | Entire data centre failure | Preferred where the region supports zones |
| Multiple regions | Whole region disaster | Highest resilience, highest cost and complexity |
Keeping all your eggs in one basket is a single VM. Using several baskets on the same shelf is an availability set. Putting baskets on shelves in three separate buildings is zones. Keeping a spare set in another city is a second region.
Service agreements
Azure publishes uptime commitments, called service level agreements, that depend on your design. Generally, a single VM using premium storage receives a lower commitment than two or more VMs in an availability set, and spreading VMs across two or more zones earns the highest commitment. Exact percentages change, so always check Microsoft’s current documentation before quoting numbers to stakeholders.
Proximity versus resilience
Proximity placement groups ask Azure to keep machines physically close, reducing delay between them. This helps tightly coupled systems but works against spreading for resilience, because closeness concentrates risk. Use it only when the delay between machines is genuinely critical.
flowchart TD
USER[Users] --> LB[Zone-redundant Load Balancer]
LB --> Z1[Zone 1 VM]
LB --> Z2[Zone 2 VM]
LB --> Z3[Zone 3 VM]
Z1 --> DB[(Replicated Data Tier)]
Z2 --> DB
Z3 --> DB
Spreading VMs across zones does not by itself make the application highly available. The application and its data must also be designed to run on several machines at once, with data replicated between them. Redundant machines running a non-redundant database still have a single point of failure.
11Scaling with Virtual Machine Scale Sets
When demand changes by the hour, adding and removing machines automatically beats guessing in advance.
Vertical versus horizontal scaling
Scaling up, also called vertical scaling, means moving to a bigger machine. It is simple but has a ceiling, usually needs a restart and leaves a single point of failure. Scaling out, called horizontal scaling, means adding more machines of the same size. It has no practical ceiling and improves resilience, but the application must be able to run on several machines at once.
If your supermarket has long queues, you can hire a faster cashier (scale up) or open more checkout lanes (scale out). Faster cashiers eventually hit human limits; more lanes can keep growing as long as the shop floor has space.
What a scale set is
A virtual machine scale set manages a group of VMs created from the same definition. You describe the template once, and the scale set creates, replaces and removes instances for you. It integrates with load balancers, so new instances automatically start receiving traffic and removed ones stop.
Autoscaling
Autoscale rules adjust the instance count based on measurements or on a clock. A rule might add machines when average processor use stays above a threshold for several minutes, and remove them when it falls below a lower threshold. Schedules can pre-warm capacity before known busy periods such as a sale or a payroll run. Setting a minimum count preserves availability, and a maximum count caps cost.
Measure
Azure Monitor collects metrics such as processor use or queue length from every instance.
Evaluate
Rules compare averaged measurements against thresholds over a time window, which prevents reacting to a single spike.
Act
The scale set creates or deletes instances from the shared template.
Cool down
A waiting period lets the new capacity take effect before the next decision, avoiding constant flapping up and down.
Orchestration modes
Scale sets come in modes that differ in how much control you have over individual instances. The flexible mode lets you mix sizes, spread instances across zones and fault domains, and manage instances more like regular VMs. The uniform mode keeps every instance identical and is simpler for large stateless fleets. Microsoft’s guidance generally favours the flexible mode for new designs, though you should confirm current recommendations.
Rolling upgrades and health
Scale sets can update instances in small batches, checking health after each batch before continuing. Automatic instance repair replaces instances that fail health checks. This means a bad release can be stopped before it reaches every machine, and a crashed machine is replaced without human involvement.
Storing user sessions or uploaded files on an individual instance. When the scale set removes that instance, the data vanishes. Keep state in shared services such as databases, caches or storage accounts, and treat instances as disposable.
12Pricing and Cost Optimisation
The cloud’s greatest strength, easy spending, is also its greatest risk. Knowing the price levers is a core engineering skill.
What you pay for
A running VM’s bill has several parts: the compute charge for the size, charged by the second in most cases; the cost of managed disks, which is charged for provisioned capacity whether or not it is full; network data leaving Azure, since incoming data is generally free; any licences included in the price; and extras such as backup, monitoring storage and public addresses.
States and billing
Stopping a VM from inside its operating system does not stop the charge, because Azure still holds the reserved hardware for you. Only when a VM reaches the deallocated state, which releases the compute resources, does the compute charge stop. Disks and public addresses continue to bill during deallocation. This distinction catches many teams by surprise.
| State | Compute Billed? | Disks Billed? | Meaning |
|---|---|---|---|
| Running | Yes | Yes | Machine is on and serving work |
| Stopped (inside the OS) | Yes | Yes | Operating system is off but hardware is still reserved |
| Stopped (deallocated) | No | Yes | Hardware released; may receive a different host on restart |
| Deleted | No | Only if disks remain | VM object removed; leftovers may still exist |
Purchasing options
Pay as you go
No commitment, highest hourly rate, ideal for experiments and unpredictable work.
Reservations
Commit to a specific size and region for one or three years in return for a large discount. Best for steady, predictable machines.
Savings plans
Commit to an hourly spending amount rather than a specific size, gaining discounts with more flexibility across sizes and regions.
Spot VMs
Use Azure’s spare capacity at deep discounts, accepting that Azure can evict the machine with short notice when it needs the capacity back.
Hybrid Benefit
Apply eligible existing Windows Server or SQL Server licences to reduce the cost of those licences in Azure.
Dev and test pricing
Reduced rates for non-production subscriptions held by eligible subscribers.
Pay as you go is a taxi. Reservations are a monthly lease on a car. Savings plans are a pre-paid transport card usable on any vehicle. Spot VMs are standby seats sold cheaply because the airline may need them back.
Practical cost habits
Right-size regularly
Review utilisation monthly. Machines that never exceed twenty percent processor use are candidates for smaller sizes.
Schedule shutdowns
Development and test machines rarely need to run at night or at weekends. Automatic deallocation can cut their cost by more than half.
Commit after learning
Buy reservations or savings plans only for workloads whose steady usage you have observed for months.
Tag and report
Label every resource with owner, project and environment so costs can be attributed and forgotten machines can be traced to a person.
Clean up leftovers
Search regularly for unattached disks, unused public addresses and old snapshots.
Using Spot machines for work that cannot tolerate interruption, such as a primary database. Spot suits batch jobs, rendering, testing and stateless workers that can restart safely.
13Security for Azure Virtual Machines
With IaaS, security is a shared job. Microsoft secures the building and hardware; you secure everything you install and configure.
The shared responsibility model
Microsoft is responsible for physical security, the host, the hypervisor and the network fabric. You are responsible for the operating system configuration, patching, installed software, accounts, data and network rules. Forgetting this split is the root of many cloud breaches: people assume the provider handles patching that actually belongs to them.
A landlord provides a sturdy building, locked entrances and fire alarms. The tenant decides whether to lock their own apartment door, who gets a key and what valuables to keep inside.
Layers of defence
Identity and Access
Use Microsoft Entra ID sign-in for VMs, role-based access control for management actions, multi-factor authentication and the principle of least privilege.
Network
Private subnets, tight security group rules, no direct internet management ports, and traffic inspection through a firewall for sensitive designs.
Host and Boot
Trusted launch with Secure Boot and virtual TPM protects against rootkits and tampered boot sequences.
Data
Encryption at rest with platform or customer-managed keys, and encryption in transit using modern secure protocols.
Operating System
Regular patching, removal of unneeded services, endpoint protection and hardened baselines.
Monitoring
Central logging and threat detection so that attacks are noticed in minutes rather than months.
Managed identities instead of stored passwords
Applications on a VM often need to call other Azure services such as storage or a key vault. Rather than saving a password or secret in a configuration file, where it can leak, a VM can be given a managed identity. Azure creates and rotates the credentials automatically, and the VM proves who it is without any secret ever being written down. This removes a whole category of leaks.
Confidential computing
Some Azure VM sizes use hardware features that encrypt data even while it is being processed in memory, so that even the cloud operator cannot read it. These confidential VMs suit regulated industries such as finance and healthcare, and multi-party analytics where companies pool sensitive data without exposing it to each other.
Defender for Cloud and just-in-time access
Microsoft Defender for Cloud assesses your machines against security recommendations, flags weaknesses such as missing updates or open ports, and can detect suspicious behaviour. Just-in-time access keeps management ports closed and opens them for a specific person, from a specific address, for a limited time after an approval. Even if an attacker scans your public addresses, the door is shut almost all the time.
Patching
Azure Update Manager can assess missing updates across many machines and schedule installation in maintenance windows, including machines outside Azure. Automatic guest patching can apply critical updates in a controlled, staged way. Since unpatched software is among the most common reasons for compromise, a documented patching routine is not optional.
Problem
Administrative ports are open to the entire internet so that engineers can log in from anywhere.
Why It’s Harmful
Automated scanners find open management ports within minutes and attack them continuously with password guesses and known exploits. A single weak password can hand an attacker the machine and everything reachable from it.
Correct Approach
Remove public management access. Use Azure Bastion or a private connection, require multi-factor sign-in, and open ports only through approved just-in-time requests.
14Monitoring, Logging and Diagnostics
You cannot fix what you cannot see. Good observation turns outages into short, understood events.
Three kinds of signal
Observability rests on three kinds of information. Metrics are numbers measured over time, such as processor percentage or disk operations per second; they are light, fast and perfect for alerts. Logs are detailed records of events, such as error messages and sign-in attempts; they explain why something happened. Traces follow a single request across several services, showing where time was spent.
A car’s dashboard dials are metrics: speed, fuel, temperature. The engine diagnostic report is the logs: detailed codes for what went wrong. A delivery tracking page is a trace: it follows one parcel through every stop.
Azure tools
Platform metrics
Collected automatically from the host with no setup: processor use, disk activity and network traffic. They cannot see inside the operating system, such as memory used.
Azure Monitor Agent and data collection rules
A small agent inside the VM collects guest-level information such as memory, operating system logs and application logs, sending them to a central workspace according to rules you define.
VM insights
Ready-made dashboards showing performance and the dependencies between machines, helpful for understanding which services talk to which.
Log Analytics workspace
A central store where logs from many machines and services can be searched and analysed with a query language.
Boot diagnostics
Captures screenshots and serial output of the startup process, a lifesaver when a machine will not boot or cannot be reached over the network.
Resource Health and Service Health
Tell you whether a problem is with your resource or with the Azure platform itself, which saves hours of wrongly debugging your own application.
Alerts that people actually act on
Alerts should be few, meaningful and tied to a documented response. If every small wobble sends a message, people learn to ignore them, a condition known as alert fatigue. A good alert signals that a user-facing symptom is happening or about to happen, such as sustained errors or a disk nearing capacity, rather than merely that a number twitched.
Decide what healthy means
Agree on targets for response time, error rate and availability before choosing thresholds.
Collect the right data
Combine host metrics with guest logs so you can see both the machine and what runs inside it.
Create actionable alerts
Send each to the right group with a link to a short runbook describing what to check first.
Review after incidents
Each outage should end with one improved alert or dashboard, so the same surprise never repeats.
Watch memory and disk free space as well as processor use. Running out of disk space is one of the most common and most avoidable causes of sudden outages.
15Backup, Recovery and Disaster Planning
High availability keeps you running through small failures. Backup and disaster recovery let you come back from large ones and from human mistakes.
Why availability is not backup
If someone deletes an important file, or ransomware encrypts a disk, a redundant copy simply replicates the damage. Redundancy protects against hardware failure, not against bad changes. Backup keeps older, separate points in time that you can return to.
Two key measurements
A business deciding its RPO and RTO is deciding how much money it will spend on protection. A target of zero data loss and zero downtime is extremely costly, so each application should be given the level it truly justifies.
Azure Backup
Azure Backup takes scheduled, application-consistent copies of VMs and stores them in a vault, a protected container separate from the VM. Policies define how often backups run and how long they are kept, from daily copies for a month to monthly and yearly copies for compliance. Features such as soft delete keep deleted backups recoverable for a period, protecting against attackers or mistakes that try to destroy backups too. Restores can bring back a whole VM, individual disks or even single files.
Azure Site Recovery
Site Recovery continuously replicates VMs to another region, or from an on-premises site to Azure. If the primary location fails, you fail over, which means switching to the replica. Recovery plans define the order in which groups of machines should start, so the database comes up before the application that depends on it. Regular test failovers, which run in an isolated network without disturbing production, prove the plan works.
| Tool | Main Purpose | Typical Recovery Scope |
|---|---|---|
| Snapshots | Quick point-in-time safety before a change | One disk, same region |
| Azure Backup | Long-term, policy-driven retention | VM, disk or file |
| Site Recovery | Fast regional failover | Whole application across regions |
| Zone redundancy | Surviving a data centre loss | Automatic within a region |
Never testing restores. A backup that has not been restored in a drill is only a hope. Schedule regular recovery tests and record how long they actually take.
16Automation, Deployment and Lifecycle Management
Clicking through a portal is fine for learning. Production systems are built by repeatable, reviewable automation.
Ways to create VMs
Azure resources can be created through the web portal, command-line tools, programming libraries and declarative templates. A declarative template describes the desired end result, such as “three machines of this size in these zones”, and the platform works out the steps. Azure’s own template languages are ARM templates and the simpler Bicep, and widely used independent tools such as Terraform can manage Azure resources too. The principle matters more than the tool: infrastructure should be described in files that are stored, reviewed and versioned like software.
Why automation matters
Advantages
- Environments become repeatable: development, testing and production match.
- Changes are reviewed by colleagues before they reach production.
- Disaster rebuilds take minutes instead of weeks of memory and guesswork.
- History shows who changed what and when.
- Policies can be checked automatically before deployment.
Disadvantages / Trade-offs
- There is an initial learning and set-up effort.
- Manual emergency changes can drift from the stored definition if not captured afterwards.
- Poorly designed templates can replicate mistakes at scale.
Configuring what is inside the machine
Creating the VM is only half the job; software must also be installed and configured. Options include baking everything into a custom image, using initialisation instructions that run at first boot, VM extensions that install agents and run configuration, and dedicated configuration tools. Baking into images gives the fastest, most predictable start; first-boot configuration gives more flexibility. Many teams combine both, baking slow-changing items and configuring fast-changing ones at start-up.
Governance with policy and tags
Azure Policy lets an organisation set rules that are enforced automatically, such as “only approved regions”, “only certain sizes”, “all disks must be encrypted” or “every resource needs an owner tag”. Resource locks can prevent accidental deletion of critical resources. Together, these controls keep many teams working safely in a shared environment.
The lifecycle of a VM
flowchart LR
A[Design] --> B[Build from template]
B --> C[Configure and secure]
C --> D[Run and monitor]
D --> E[Patch and update]
E --> D
D --> F[Resize or replace]
F --> D
D --> G[Retire and clean up]
Treat machines like cattle, not pets. A pet has a name, is nursed when sick and is irreplaceable. Cattle are numbered and replaced when they fail. Designing for replacement makes recovery and updates routine.
17Migrating Existing Servers to Azure
Most real-world VM use begins with existing servers that need a new home.
The common strategies
Rehost
Lift and shift: move the machine as is. Fastest, least change, and gains little beyond location.
Replatform
Make small adjustments, such as moving a database to a managed service, while leaving the application structure alone.
Refactor
Redesign the application to use cloud-native services. Highest effort and highest long-term benefit.
Retire or retain
Switch off servers nobody uses, or keep some workloads where they are for legal or technical reasons.
The migration journey
Discover
Inventory every server, what it runs, how busy it is and what it talks to. Hidden dependencies are the biggest source of failed migrations.
Assess
Check readiness, estimate Azure sizes based on real usage rather than the size of the old hardware, and forecast cost.
Prepare the landing zone
Build the network, identity, policy and monitoring foundations before the first server arrives.
Replicate and test
Copy data continuously to Azure and run test cutovers that do not affect production.
Cut over and optimise
Switch users to the Azure copy during a planned window, then right-size and apply savings options once real usage is known.
Azure Migrate is Microsoft’s central service for discovery, assessment and migration of servers, databases and applications. It scans environments, recommends sizes, estimates cost and orchestrates replication and cutover.
Sizing Azure machines to match the old hardware. Old servers were usually bought with large safety margins and run at low utilisation. Sizing from measured usage avoids paying for capacity that was never needed.
18Performance Tuning and Operational Best Practices
A well-chosen VM can still underperform if its surroundings are poorly arranged.
Finding the bottleneck
Performance problems usually come from one of four places: processor, memory, disk or network. Slowness is rarely spread evenly, so the first step is identifying which resource is saturated. A machine with low processor use but long disk queues is waiting on storage, and buying more processors would only waste money.
Processor
Sustained high use suggests a larger or more compute-focused size, or more instances behind a load balancer.
Memory
High swapping or paging signals too little memory; move to a memory-optimised family or fix leaks in the application.
Disk
Long queues or throttling point to a faster disk type, striping several disks together, or a size with higher disk limits.
Network
Throttled bandwidth or high delay suggests accelerated networking, a bigger size or moving chatty machines closer together.
Throttling explained
Both the VM size and each disk have performance ceilings. When demand hits either ceiling, Azure slows requests down rather than failing them. The result is mysterious slowness with no errors. Checking throttling metrics early saves hours of misdirected investigation.
Operational habits that pay off
Separate concerns across disks
Keep operating system, data and logs on distinct disks so each can be sized, tuned and protected on its own.
Use newer generations
Move off old hardware generations when practical; they often deliver more speed per currency unit.
Keep time and names consistent
Accurate clocks and clear naming conventions make logs comparable and resources easy to identify during incidents.
Document runbooks
Write short step-by-step guides for common events such as disk full, failed patch and failover, and keep them where the on-call engineer can find them at three in the morning.
Review architecture periodically
Use the Azure Well-Architected Framework, which organises good practice into reliability, security, cost, operational excellence and performance, as a regular checklist.
Problem
A lovingly hand-built server is configured by many people over years with undocumented changes, and nobody knows exactly how it works.
Why It’s Harmful
If it fails, nobody can rebuild it identically. Updates become frightening, and knowledge lives in the heads of a few people who may leave.
Correct Approach
Capture the configuration in images and templates, keep the definition under version control, and rebuild machines regularly so drift cannot accumulate.
Problem
Everything is placed in one subscription, one network and one resource group with no naming, tagging or ownership rules.
Why It’s Harmful
Costs cannot be attributed, access is too broad, and a single mistake can affect unrelated systems.
Correct Approach
Separate environments and teams into their own subscriptions or resource groups, adopt consistent naming and tags, and enforce standards with policy.
19Advantages, Limitations and Trade-offs
Every technology choice trades something for something else. Being honest about both sides leads to better decisions.
Advantages
- Full control over the operating system, software and configuration.
- Runs almost any workload, including old or specialised software that cannot be changed.
- Fast creation and removal with no hardware purchase.
- A huge range of sizes, including graphics and high-performance options.
- Global reach with many regions and zone-based resilience.
- Rich choices for pricing, from flexible to heavily discounted commitments.
Disadvantages / Trade-offs
- You own patching, hardening, monitoring and backup, which takes continuous effort.
- Idle or oversized machines waste money silently.
- Resilience requires deliberate design; it is not automatic.
- Costs can be complex because they include disks, networking, licences and extras.
- Managed platforms can offer lower operational burden for many standard workloads.
Deciding between VMs and alternatives
A useful test is to ask what you gain from controlling the operating system. If the answer is “nothing in particular”, a managed platform will probably cost less effort. If the answer is “we need a specific kernel setting, an unusual driver, a licensed server product or a particular directory layout”, a VM is the correct tool. Many organisations run a mixture, using managed services where they fit and VMs where control is essential.
20Real-World Scenarios
Patterns become clear when you see them applied. These are typical industry uses, described generally.
Lift-and-shift of a company data centre
A manufacturer with ageing servers moves hundreds of machines to Azure to avoid a hardware refresh. They discover that most servers were oversized, so after measuring, they run on smaller sizes, then buy reservations for the stable ones and shut development servers down at night.
Retail sales peaks
An online shop runs its web tier on a scale set across three zones. During a festival sale, autoscale grows the tier many times over, then shrinks it afterwards. A schedule pre-warms capacity thirty minutes before the sale starts so customers never wait for scaling to react.
Enterprise databases and licensed software
A bank runs a commercial database that requires specific server settings. It chooses memory-optimised machines with premium disks, applies existing licences through Hybrid Benefit, replicates data across zones and uses Site Recovery for regional failover.
Machine learning and rendering
A studio and a research team rent GPU machines for a few days to train models or render frames, then delete them. Spot capacity handles interruptible batches at a fraction of the normal price, with checkpoints so work resumes after an eviction.
Remote developer workstations
A software company gives engineers cloud workstations with standardised tools. Machines are created from a golden image, start and stop on schedules, and keep source code off personal laptops, improving both consistency and security.
Regulated and confidential workloads
A hospital group analyses patient data on confidential VMs with customer-managed keys, private networking only and full audit logging, meeting strict privacy rules while still using cloud elasticity.
21A Reference Architecture Walkthrough
Let us assemble the earlier chapters into one sensible design for a typical business web application.
Imagine a company application with a web front end, a business logic layer and a database. The goals are availability across a data centre failure, safe administration, controlled cost and easy recovery. The design below shows how the ideas fit together.
flowchart TD
USER[Users on Internet] --> GW[Application Gateway with web firewall]
GW --> WEB[Web tier scale set across zones]
WEB --> ILB[Internal Load Balancer]
ILB --> APP[App tier VMs across zones]
APP --> DB[(Database tier with replication)]
ADMIN[Administrators] --> BAS[Azure Bastion]
BAS -.private access.-> WEB
BAS -.private access.-> APP
MON[Azure Monitor and Log Analytics] -.collects.-> WEB
MON -.collects.-> APP
MON -.collects.-> DB
BKP[Backup vault] -.protects.-> APP
BKP -.protects.-> DB
DB -.replicates.-> DR[(Secondary region replica)]
Walking through the design
Single public entry point
Only the gateway has a public address. It inspects web traffic for common attacks and forwards clean requests to the web tier.
Web tier as a scale set
Stateless web machines spread across three zones grow and shrink with demand and are replaced automatically if unhealthy.
Private application and data tiers
Application and database machines live in private subnets with strict rules that allow only the necessary conversations between layers.
Safe administration
Engineers connect through Bastion with multi-factor sign-in. No machine exposes a management port to the internet.
Observability and protection
All tiers send logs and metrics to a central workspace; backups run on policy; the database replicates to a second region for disaster recovery.
Why this works
Each risk is covered by a specific design decision. Machine failure is handled by redundancy, data centre failure by zones, regional disaster by replication, human error by backup, attacks by layered network and identity controls, and demand swings by autoscale. Cost control comes from right-sizing, schedules and commitments for the steady parts.
22Frequently Asked Questions
Stopping from inside the operating system leaves the hardware reserved and compute billing continues. Deallocating releases the hardware, so compute charges end, although disks and some addresses still cost money. Use the Azure-level stop action, which deallocates, to save money.
Yes. Resizing usually requires a restart, and the new size must be available in the hardware cluster hosting the machine. If it is not, deallocating first often allows the move to another cluster. Plan resizing for a maintenance window.
Disks are separate resources. Depending on the option chosen at creation or deletion, they may be deleted with the VM or left behind. Always check, and keep backups for anything valuable.
Contents of the temporary disk and the contents of memory may be lost when a machine is redeployed. The OS disk and data disks persist because they are stored separately from the host.
No. Many secure designs use only private addresses and reach machines through Bastion, a VPN, a private circuit or a load balancer. Fewer public addresses means a smaller attack surface.
You do. Azure patches the host beneath your VM, but the guest operating system and its software are your responsibility. Update Manager and automatic guest patching can help automate it.
Not necessarily. If the bottleneck is disk speed, network bandwidth or application design, adding processors changes little. Measure first, then change the resource that is actually saturated.
Use them for interruptible, restartable work such as batch processing, rendering, testing and stateless workers. Avoid them for primary databases and anything that must stay up continuously.
A reservation commits to a particular size and region and gives a deep discount for that specific usage. A savings plan commits to an hourly spend and applies more flexibly across sizes and regions, usually with a somewhat smaller discount.
An availability set spreads machines across racks and update groups inside one data centre. Availability zones spread machines across separate data centres in a region, protecting from larger failures. Zones are generally preferred where available.
Yes, through an encrypted VPN tunnel over the internet or a private dedicated circuit using ExpressRoute. Address ranges must not overlap between the two networks.
Managed databases remove patching, backup and failover work and suit most cases. Run a database on VMs only when you need features, versions or settings that managed services do not offer, and be ready to own its operations.
Set budgets with alerts, tag resources with owners, schedule shutdowns for non-production machines, review unattached disks and addresses, and examine cost reports regularly.
It is an identity Azure creates and manages for a resource so that it can authenticate to other services without stored passwords. It removes the risk of leaked secrets in configuration files.
Yes, when designed properly. Large organisations worldwide run critical systems on them. Safety depends on your choices around redundancy, security, patching, monitoring and backup, not on the platform alone.
23Summary and Key Takeaways
An Azure Virtual Machine is a software-defined computer running on Microsoft’s hardware, rented by the second and shaped to your needs. It gives you the freedom of a real server without the delay and cost of buying one. In exchange, you accept responsibility for what runs inside it: the operating system, the security settings, the updates, the monitoring and the recovery plan. Everything around the VM, including disks, networks, zones, scale sets, backup and policy, exists to help you carry that responsibility well. The skill is not in creating a machine, which takes minutes, but in designing the whole system so that it stays fast, safe, available and affordable for years.
Key Takeaways
- A VM is a family of resources — compute, disks, network card, addresses and security rules are separate pieces that must be managed and cleaned up together.
- Choose size by evidence — match the family to the workload, check disk and network limits as well as vCPUs, and review utilisation regularly.
- Design for failure — use availability zones, load balancing and replicated data, because one VM in one place is one point of failure.
- Security is shared — Microsoft secures the platform; you secure the guest, with private networking, strong identity, managed identities, patching and monitoring.
- Scale out, not just up — scale sets with autoscale and stateless design handle changing demand and replace failed machines automatically.
- Control cost deliberately — deallocate idle machines, right-size, commit with reservations or savings plans for steady loads, and use Spot only for interruptible work.
- Automate and test recovery — describe infrastructure in versioned templates, build from golden images, and prove your backups and failover by restoring them regularly.