Deploying a Three-Tier Architecture in Azure Using Azure CLI

In this comprehensive guide, we'll walk through the process of creating a three-tier architecture in Azure using Azure CLI commands in PowerShell. This architecture separates the application into web, application, and database tiers, providing better scalability, security, and maintenance capabilities.

Prerequisites

  • Azure CLI installed

  • PowerShell environment

  • An active Azure subscription

  • Basic understanding of networking concepts

Architecture Overview

Our three-tier architecture consists of:

  • Web Tier (Public-facing)

  • Application Tier (Middle layer)

  • Database Tier (Backend)

Each tier is isolated in its own subnet within a virtual network, following security best practices.

Step-by-Step Implementation

1. Setting Up Variables

First, we'll define our PowerShell variables:

$resourceGroupName = "Siddhant-ThreeTierArchitecture-rg"
$location = "westus"
$vnetName = "Siddhant-ISMT-Vnet"
$webSubnetName = "Siddhant-ISMT-webSubnet"
$appSubnetName = "Siddhant-ISMT-appSubnet"
$dbSubnetName = "Siddhant-ISMT-dbSubnet"
$publicIPName = "Siddhant-ISMT-PublicIP"

2. Creating the Resource Group

Create a new resource group to contain all our resources:

az group create --name $resourceGroupName --location $location

3. Setting Up the Network Infrastructure

Create the virtual network with three subnets:

# Create VNet with web subnet
az network vnet create --resource-group $resourceGroupName --location $location --name $vnetName --address-prefixes 10.0.0.0/16 --subnet-name $webSubnetName --subnet-prefixes 10.0.1.0/24

# Create application subnet
az network vnet subnet create --resource-group $resourceGroupName --vnet-name $vnetName --name $appSubnetName --address-prefix 10.0.2.0/24

# Create database subnet
az network vnet subnet create --resource-group $resourceGroupName --vnet-name $vnetName --name $dbSubnetName --address-prefix 10.0.3.0/24

4. Creating Public IP Address

Set up a static public IP for the load balancer:

az network public-ip create --resource-group $resourceGroupName --name $publicIPName --sku Standard --allocation-method Static

5. Setting Up Load Balancer

Create a load balancer to distribute traffic:

az network lb create --resource-group $resourceGroupName --name webLoadBalancer --sku Standard --public-ip-address $publicIPName --frontend-ip-name webFrontEnd --backend-pool-name webBackEndPool

6. Configuring Network Security

Create and configure Network Security Group (NSG):

# Create NSG
az network nsg create --resource-group $resourceGroupName --name webNSG

# Add rule to allow HTTP traffic
az network nsg rule create --resource-group $resourceGroupName --nsg-name webNSG --name allowHTTP --protocol tcp --direction inbound --source-address-prefix '*' --source-port-range '*' --destination-port-range 80 --access allow --priority 100

# Add rule to allow SSH 
az network nsg rule create --resource-group $resourceGroupName --nsg-name webNSG --name allowssh --protocol tcp --direction inbound --source-address-prefix '*' --source-port-range '*' --destination-port-range 22 --access allow --priority 101

7. Deploying Virtual Machines

Create VMs for web and application tiers:

# Create Web VM
az vm create --resource-group $resourceGroupName --name webVM1 --image Ubuntu2204 --vnet-name $vnetName --subnet $webSubnetName --nsg webNSG --size Standard_B1s --admin-username azureuser --generate-ssh-keys

# Create Application VM
az vm create --resource-group $resourceGroupName --name appVM1 --image Ubuntu2204 --vnet-name $vnetName --subnet $appSubnetName --nsg webNSG --size Standard_B1s --admin-username azureuser --generate-ssh-keys

8. Configuring Load Balancer Backend Pool

Add VMs to the load balancer backend pool:

# Add Web VM to backend pool
az network lb address-pool address add --resource-group $resourceGroupName --lb-name webLoadBalancer --pool-name webBackEndPool -n webVM1 --vnet $vnetName --ip-address 10.0.1.4

# Add App VM to backend pool
az network lb address-pool address add --resource-group $resourceGroupName --lb-name webLoadBalancer --pool-name webBackEndPool -n appVM1 --vnet $vnetName --ip-address 10.0.2.4

Architecture Deep Dive

Network Design

  • VNet Address Space: 10.0.0.0/16

    • Web Tier Subnet: 10.0.1.0/24

    • Application Tier Subnet: 10.0.2.0/24

    • Database Tier Subnet: 10.0.3.0/24

Security Implementation

  1. Network Segmentation

    • Each tier is isolated in its own subnet

    • Traffic flow is controlled between tiers

    • Public access is limited to the web tier only

  2. NSG Configuration

    • Inbound HTTP (port 80) allowed to web tier

    • Inter-subnet communication controlled

    • Database tier protected from direct external access

  3. Load Balancer Security

    • Standard SKU for enhanced security

    • Static IP allocation

    • Backend pool health monitoring

Benefits of This Architecture

  1. High Availability

    • Load balanced web tier

    • Multiple VMs for redundancy

    • Ability to scale each tier independently

  2. Security

    • Layered security approach

    • Network segregation

    • Controlled communication paths

  3. Maintainability

    • Independent tier management

    • Easy to update components

    • Simplified troubleshooting

  4. Scalability

    • Horizontal scaling capabilities

    • Independent tier scaling

    • Load balancer distribution

Best Practices and Recommendations

  1. Monitoring

    • Enable Azure Monitor

    • Set up alerts for resource metrics

    • Configure diagnostic logging

  2. Backup Strategy

    • Regular VM backups

    • Database backup and replication

    • Configuration backup

  3. Security Enhancements

    • Implement Azure Bastion for secure VM access

    • Use Azure Key Vault for secrets

    • Regular security patches and updates

  4. Cost Optimization

    • Right-size VMs based on usage

    • Use auto-scaling where appropriate

    • Monitor and optimize resource usage

Maintenance Guidelines

  1. Regular Updates

    • Schedule monthly maintenance windows

    • Apply security patches promptly

    • Update NSG rules as needed

  2. Monitoring and Alerts

    • Set up CPU and memory thresholds

    • Monitor network traffic patterns

    • Configure availability alerts

  3. Disaster Recovery

    • Document recovery procedures

    • Regular backup testing

    • Failover scenario planning

Conclusion

This three-tier architecture implementation provides a robust foundation for enterprise applications in Azure. The PowerShell commands make it easy to automate the deployment process, while the security measures and best practices ensure a reliable and maintainable solution.

Remember to:

  • Regularly review and update security configurations

  • Monitor resource usage and performance

  • Keep documentation updated

  • Test disaster recovery procedures

  • Optimize based on actual usage patterns

This architecture can be further customized based on specific requirements while maintaining the core principles of separation of concerns and security.

[Previous sections remain same until Load Balancer Backend Pool configuration]

Website Deployment on Virtual Machine

9. SSH into the Web VM

After setting up the infrastructure, we need to SSH into the web VM to deploy our website. First, get the public IP of the web VM:

# Get the public IP of the web VM
$webVMIP = az vm show -d -g $resourceGroupName -n webVM1 --query publicIps -o tsv

# SSH into the web VM
ssh azureuser@$webVMIP

10. Create and Execute Deployment Script on VM

Once you're connected to the VM via SSH, create and execute the deployment script:

# Create deployment script
sudo nano /home/azureuser/deploy-website.sh

Copy and paste the following content into the script:

#!/bin/bash
# Ensure the script is run with root privileges
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

# Step 1: Update the operating system packages
apt update -y

# Step 2: Install Nginx
apt install nginx -y

# Step 3: Navigate to /var/www and create a folder named your_domain.com
cd /var/www
mkdir mystic.com
cd mystic.com

# Step 4: Clone the GitHub repository into the directory
# Ensure git is installed or handle its absence
if ! command -v git &> /dev/null
then
    echo "git could not be found, installing now..."
    apt install git -y
fi
git clone https://github.com/siddhantbhattarai/e-commerce-static-site.git .

# Step 5: Configure Nginx to serve your site
cd /etc/nginx/sites-available/

# Create Nginx configuration file
sudo tee mystic.com <<EOF
server {
    listen 80;
    listen [::]:80;
    server_name mystic.com;
    root /var/www/mystic.com;
    index index.html;
    location / {
        try_files \$uri \$uri/ =404;
    }
}
EOF

# Create a symlink to enable the site
ln -s /etc/nginx/sites-available/mystic.com /etc/nginx/sites-enabled/

# Optional: Remove the default Nginx site configuration to avoid conflicts
rm /etc/nginx/sites-enabled/default

# Step 7: Test Nginx configuration for syntax errors
nginx -t

# Step 8: Restart Nginx to apply the changes
systemctl restart nginx

# Display a success message
echo "Nginx has been configured to serve your site and restarted successfully!"

Save the file (in nano: Ctrl+X, then Y, then Enter)

Now make the script executable and run it:

# Make script executable
sudo chmod +x /home/azureuser/deploy-website.sh

# Run the script
sudo bash /home/azureuser/deploy-website.sh

11. Verify Website Deployment

Once the script has finished running, you can verify the website is accessible through the load balancer:

# Exit from the VM SSH session
exit

# Get the load balancer's public IP
$lbIP = az network public-ip show --resource-group $resourceGroupName --name $publicIPName --query ipAddress -o tsv

Write-Host "Website is accessible at: http://$lbIP"

12. Clean Up Resources

When you're done with the infrastructure, clean up all resources:

# Delete the entire resource group and all resources within it
Write-Host "Cleaning up all resources..."
az group delete --name $resourceGroupName --yes --no-wait

Write-Host "Resource deletion has been initiated. This process may take several minutes to complete."

Verification Steps

  1. Website Deployment Verification:

    • Verify Nginx is running: sudo systemctl status nginx

    • Check website files: ls -la /var/www/mystic.com

    • Test Nginx configuration: sudo nginx -t

    • View error logs if needed: sudo tail -f /var/log/nginx/error.log

  2. Load Balancer Verification:

    • Check if website is accessible through load balancer IP

    • Verify HTTP port 80 is open and responding

    • Check load balancer health probe status

  3. Resource Cleanup Verification:

    • Monitor resource group deletion progress in Azure portal

    • Verify all resources are removed

    • Check for any lingering resources or dependencies

Troubleshooting Common Issues

  1. SSH Connection Issues:

     # Verify VM is running
     az vm show -d -g $resourceGroupName -n webVM1 --query powerState
    
     # Verify NSG rules
     az network nsg rule list --resource-group $resourceGroupName --nsg-name webNSG -o table
    
  2. Website Deployment Issues:

     # Check Nginx status
     sudo systemctl status nginx
    
     # View Nginx error logs
     sudo tail -f /var/log/nginx/error.log
    
     # Check website directory permissions
     ls -la /var/www/mystic.com
    
  3. Load Balancer Issues:

     # Check load balancer health
     az network lb probe list --resource-group $resourceGroupName --lb-name webLoadBalancer -o table
    
     # Verify backend pool configuration
     az network lb address-pool list --resource-group $resourceGroupName --lb-name webLoadBalancer -o table
    

Best Practices for Production

  1. Security:

    • Use SSH key-based authentication

    • Implement proper firewall rules

    • Regular security updates

    • Use HTTPS with SSL/TLS certificates

  2. Monitoring:

    • Set up Azure Monitor

    • Configure alerts

    • Monitor resource usage

    • Keep logs for troubleshooting

  3. Maintenance:

    • Regular backups

    • Scheduled updates

    • Performance optimization

    • Documentation updates

Remember to always verify the website is working correctly before cleaning up the resources, and ensure all necessary data is backed up before deletion.