Network Security Groups (NSGs) are a fundamental component of Azure's networking capabilities, providing network security at the subnet and virtual machine (VM) network interface (NIC) levels. They act as a virtual firewall, allowing you to define inbound and outbound security rules to filter network traffic.
An NSG contains a list of security rules that allow or deny network traffic to resources connected to Azure Virtual Network (VNet). NSGs can be associated with:
When an NSG is associated with both a subnet and a NIC, the rules from both are applied. Security rules are processed based on priority, with lower numbers indicating higher priority. For each direction (inbound and outbound), traffic is processed by a single NSG, even if the NSG is associated with both a subnet and a NIC. The order of evaluation is:
Define traffic filtering based on source/destination IP, port, and protocol.
Apply NSGs to subnets or NICs to control traffic flow.
Rules are evaluated in order of priority (0-4096). Lower numbers have higher precedence.
Filter traffic entering (inbound) and leaving (outbound) a resource.
Every NSG contains a set of default security rules that are created automatically. You cannot delete these rules, but you can override them. The default rules are:
You can create and manage NSGs using the Azure portal, Azure CLI, Azure PowerShell, or ARM templates.
This example shows how to create an NSG, add an inbound rule to allow SSH traffic (port 22), and associate it with a subnet.
# Log in to Azure
az login
# Set your subscription context (if needed)
az account set --subscription "Your Subscription ID"
# Create a Resource Group (if you don't have one)
az group create --name MyResourceGroup --location eastus
# Create a Virtual Network and Subnet (if you don't have them)
az network vnet create \
--resource-group MyResourceGroup \
--name MyVNet \
--address-prefix 10.0.0.0/16 \
--subnet-name MySubnet \
--subnet-prefix 10.0.1.0/24
# Create a Network Security Group
az network nsg create \
--resource-group MyResourceGroup \
--name MyNSG
# Add an inbound security rule to allow SSH (port 22)
az network nsg rule create \
--resource-group MyResourceGroup \
--nsg-name MyNSG \
--name AllowSSH \
--priority 100 \
--direction Inbound \
--access Allow \
--protocol Tcp \
--source-address-prefixes '*' \
--source-port-ranges '*' \
--destination-address-prefixes '*' \
--destination-port-ranges 22
# Associate the NSG with the subnet
az network vnet subnet update \
--resource-group MyResourceGroup \
--vnet-name MyVNet \
--name MySubnet \
--network-security-group MyNSG
VirtualNetwork, Internet, AzureLoadBalancer) for easier management of common IP address ranges.NSG Flow Logs enable you to record information about the IP traffic flowing through an NSG. This data can be used to visualize traffic flows and troubleshoot network connectivity. Flow logs are stored in Azure Storage and can be analyzed using tools like Azure Monitor or Traffic Analytics.