Microsoft Docs

Configure Network Security Groups (NSG)

Network Security Groups (NSGs) allow you to filter inbound and outbound traffic to Azure resources. This guide walks you through creating an NSG, defining security rules, and associating the NSG with subnets or network interfaces.

Prerequisites

Step 1 – Create an NSG

Using Azure CLI:

az network nsg create \
    --resource-group MyResourceGroup \
    --name MyNSG \
    --location eastus

Using Azure PowerShell:

New-AzNetworkSecurityGroup -ResourceGroupName "MyResourceGroup" `
    -Location "EastUS" -Name "MyNSG"

Step 2 – Add Security Rules

Example: Allow SSH (port 22) from a specific IP address.

az network nsg rule create \
    --resource-group MyResourceGroup \
    --nsg-name MyNSG \
    --name Allow-SSH \
    --protocol Tcp \
    --direction Inbound \
    --priority 1000 \
    --source-address-prefixes 203.0.113.0/24 \
    --source-port-ranges "*" \
    --destination-address-prefixes "*" \
    --destination-port-ranges 22 \
    --access Allow

PowerShell equivalent:

New-AzNetworkSecurityRuleConfig -Name "Allow-SSH" `
    -Description "Allow SSH from office" `
    -Access Allow -Protocol Tcp -Direction Inbound `
    -Priority 1000 -SourceAddressPrefix "203.0.113.0/24" `
    -SourcePortRange "*" -DestinationAddressPrefix "*" `
    -DestinationPortRange 22 | `
    Set-AzNetworkSecurityGroup -NetworkSecurityGroup $nsg

Step 3 – Associate NSG with a Subnet

az network vnet subnet update \
    --resource-group MyResourceGroup \
    --vnet-name MyVNet \
    --name MySubnet \
    --network-security-group MyNSG

PowerShell:

$subnet = Get-AzVirtualNetworkSubnetConfig -Name "MySubnet" -VirtualNetwork $vnet
$subnet.NetworkSecurityGroup = $nsg
Set-AzVirtualNetwork -VirtualNetwork $vnet

Step 4 – Verify the Configuration

az network nsg show --resource-group MyResourceGroup --name MyNSG
Tip: Use descriptive names and comment fields for each rule to simplify future audits.

Common NSG Rule Patterns

PurposePriorityProtocolPort(s)Direction
Allow RDP from corporate VPN100Tcp3389Inbound
Deny All Internet Inbound4096**Inbound
Allow HTTP/HTTPS Outbound200Tcp80,443Outbound

Next Steps