civil-and-structural-engineering
Deploying Docker Containers on Azure Container Instances
Table of Contents
Understanding Azure Container Instances
Azure Container Instances (ACI) is Microsoft's serverless container hosting service designed to run containers in the cloud without the overhead of managing virtual machines or orchestrators. It offers a straightforward way to deploy both Linux and Windows containers, making it suitable for a wide range of scenarios — from batch processing and event-driven applications to small microservices and development environments. Unlike Azure Kubernetes Service (AKS), which requires cluster management and configuration, ACI abstracts away infrastructure complexity, allowing you to focus solely on your application.
ACI provides per-second billing, hypervisor-level isolation for security, and support for public IP addresses and DNS labels. It integrates seamlessly with Azure Networking, Azure Monitor, and Azure Container Registry, enabling you to build robust containerized solutions with minimal operational effort. For teams looking to quickly test prototypes or run short-lived workloads, ACI is an ideal choice.
Key Capabilities of ACI
- Launch containers in seconds – No provisioning delays; you can start a container in under a minute.
- Customize resource allocation – Specify CPU cores, memory, and GPU (for AI/ML workloads) for each container group.
- Support for public network access – Containers can be exposed to the internet via a public IP and FQDN.
- Virtual network integration – Deploy containers directly into an Azure Virtual Network for secure communication with other Azure resources.
- Managed identity support – Enable Azure authentication without storing credentials in your container.
- Multi-container groups – Run multiple containers sharing the same lifecycle, network, and storage (e.g., a sidecar pattern).
Prerequisites for Deploying Docker Containers on ACI
Before you begin, ensure the following components are in place:
- An active Azure subscription – Sign up for a free trial if you don’t already have an account.
- Docker Desktop – Installed on your local machine to build and test container images. Download from the official Docker website.
- Azure CLI – The command-line tool for managing Azure resources. Install it following the official Microsoft documentation.
- A container registry – Use Docker Hub, Azure Container Registry (ACR), or any OCI-compliant registry to store your image. ACR integrates natively with ACI for secure, private deployments.
Step-by-Step Deployment Process
1. Build and Tag Your Docker Image
Start by confirming your Dockerfile is production-ready. Use a Dockerfile that installs only necessary dependencies and runs your application as a non-root user for security. Build the image with a descriptive tag:
docker build -t myregistry.azurecr.io/myapp:v1 .
If using Docker Hub, replace myregistry.azurecr.io with your Docker Hub username. After building, verify the image runs correctly locally before pushing to a registry.
2. Push the Image to a Container Registry
Authenticate with your registry and push the image:
docker push myregistry.azurecr.io/myapp:v1
For Azure Container Registry, first log in using az acr login --name myregistry. This ensures you can push without storing credentials in Docker.
3. Authenticate to Azure and Set the Subscription
Open a terminal and log in to Azure:
az login
This opens a browser window for your credentials. After successful login, set the appropriate subscription if you have multiple ones:
az account set --subscription "YourSubscriptionName"
4. Create a Resource Group (If Needed)
Resource groups logically organize Azure resources. Create one or reuse an existing group:
az group create --name myResourceGroup --location eastus
Choose a location that supports ACI (check Azure region availability).
5. Deploy the Container Instance
Use the az container create command. The minimal deployment requires a name, image, resource group, and port mapping. Here’s an example exposing a web application on port 80 with a DNS label:
az container create --name mycontainer --image myregistry.azurecr.io/myapp:v1 --resource-group myResourceGroup --dns-name-label myapp --ports 80
After a few seconds, ACI pulls your image and starts the container. You can check the status with:
az container show --name mycontainer --resource-group myResourceGroup --query instanceView.state
Once Running, access your application at myapp.eastus.azurecontainer.io (where eastus is the region).
Customizing Your Deployment
A simple deployment is just the start. For production use cases, you will want to configure environment variables, restart policies, and resource limits.
Environment Variables and Secrets
Pass configuration values through environment variables. For sensitive data (e.g., passwords), use Azure Key Vault references or secure strings:
az container create --name mycontainer --image myapp:v1 --resource-group myResourceGroup --environment-variables DB_HOST=prod-db.example.com DB_PORT=5432 --secure-environment-variables DB_PASSWORD=mySecretPassword
Secure environment variables are encrypted in transit and at rest, and they are not visible in the Azure portal.
Volume Mounts for Persistent Storage
ACI supports mounting Azure Files shares, empty directories, or git repos. To attach an Azure Files share:
- First create a storage account and a file share in Azure.
- Then use the
--azure-file-volume-share-name,--azure-file-volume-account-name, and--azure-file-volume-account-keyparameters, or mount using a YAML/ARM template.
Example CLI command (partial):
az container create ... --azure-file-volume-share-name myshare --azure-file-volume-account-name mystorageaccount --azure-file-volume-account-key abc123... --mount-path /app/data
Restart Policies
ACI offers three restart policies: Always, OnFailure, and Never. Choose based on your workload type:
- Always – Restarts automatically if the container stops (default, suitable for long-running services).
- OnFailure – Restarts only when the container exits with a non-zero exit code (ideal for batch jobs).
- Never – Never restarts (useful for one-time tasks).
Set with --restart-policy OnFailure.
Resource Limits and Requests
By default, ACI allocates 1 CPU core and 1.5 GB memory per container. You can specify exact values to optimize cost and performance:
az container create ... --cpu 2 --memory 4
Memory can be up to 340 GB for certain Linux SKUs. Check the resource limits documentation for the latest.
Health Probes (Liveness and Readiness)
To improve reliability, add liveness and readiness probes. These require deploying via a YAML file or ARM template, as the CLI does not expose these directly. Example snippet for a liveness probe:
livenessProbe: { exec: { command: ["/bin/check-health.sh"] }, initialDelaySeconds: 5, periodSeconds: 10 }
Readiness probes ensure traffic reaches only healthy containers when placed behind Azure Load Balancer.
Advanced Scenarios and Integrations
Deploying into a Virtual Network
For workloads that must communicate with other Azure resources (e.g., SQL Database, AKS clusters) without public internet exposure, deploy your container into an Azure Virtual Network (VNet). This is done by specifying the VNet and subnet ID:
az container create --name myapp --image myapp:v1 --resource-group myResourceGroup --vnet myVNet --subnet mySubnet
Note: VNet deployment currently requires that the container group is the only service in that subnet. Plan your network address space accordingly.
Using Managed Identity
Enable a managed identity for your container group to authenticate to Azure services (e.g., accessing Key Vault or Blob Storage) without storing credentials. Create a container with a system-assigned identity:
az container create ... --assign-identity
After deployment, grant the identity appropriate RBAC roles. Inside the container, use the Azure SDK’s DefaultAzureCredential to authenticate.
Multi-Container Groups
ACI supports running multiple containers in a single group. Containers share the same host, network, and storage volumes. This is useful for the sidecar pattern — for example, a web server accompanied by a logging sidecar. Define the group using a YAML file:
az container create --resource-group myResourceGroup --file deploy.yaml
The YAML specifies each container’s image, ports, environment variables, and dependencies. All containers start and stop together.
Integration with Azure Monitor and Container Insights
Enable diagnostic logging and metrics for your container instance. Use the Azure portal to turn on Container Insights, which collects CPU/memory metrics, log data, and live container logs. Alternatively, configure diagnostic settings to send logs to Log Analytics for deeper querying with Kusto.
To enable from CLI, create a container with --log-analytics-workspace parameters. This gives you real-time monitoring and alerting.
Security Best Practices for ACI
- Use private container registries – Pull images from Azure Container Registry with managed identities to avoid image tampering.
- Run containers as non-root – Ensure your Dockerfile creates a non-root user. ACI supports this natively.
- Enable network segmentation – Deploy containers into a VNet with Network Security Groups (NSGs) to restrict inbound/outbound traffic.
- Keep images small and updated – Use minimal base images (e.g., Alpine, distroless) and regularly scan for vulnerabilities with tools like Defender for Cloud.
- Rotate secrets – Use Azure Key Vault references in environment variables; never hardcode secrets in images.
Cost Optimization Tips
ACI pricing is consumption-based. To control costs:
- Use spot containers (currently in preview) – Deploy interruptible workloads at up to 50% discount.
- Explicitly set CPU/memory – Avoid over-provisioning; monitor usage with Container Insights and adjust.
- Set short-lived containers – For batch jobs, use
--restart-policy Neverand clean up completed instances automatically via automation. - Consider reserved instances – If you run persistent workloads, Azure Reservations offer savings over pay-as-you-go.
Limitations to Be Aware Of
ACI is not a full orchestration platform. Key limitations:
- No built-in auto-scaling – You must implement scaling logic using Azure Functions, Logic Apps, or a custom scheduler to create and delete container groups.
- No rolling updates – Updating a container group requires destroying and recreating it (blue-green deployment pattern via separate groups).
- Maximum container group size – A single group can have up to 60 containers (depending on resource specs), but the host that runs the group has fixed resources.
- GPU SKU availability – GPU-optimized instances are available only in certain regions; check GPU documentation.
Comparing ACI with Other Azure Compute Options
| Service | Best for | Notes |
|---|---|---|
| ACI | Simple, stateless containers; batch jobs; development | Serverless, per-second billing |
| Azure Kubernetes Service (AKS) | Microservices, orchestration, complex scaling | Full orchestration, cluster management |
| Azure App Service | Web apps, APIs | Managed platform, built-in scaling |
| Azure Functions | Event-driven serverless code | Triggers, short execution time |
For many users, ACI provides an ideal middle ground: more control than App Service but less complexity than AKS.
Monitoring and Troubleshooting Your Container
After deployment, you may need to debug issues. Use these commands:
- View logs:
az container logs --name mycontainer --resource-group myResourceGroup - Attach to a container (if interactive):
az container attach --name mycontainer --resource-group myResourceGroup - Check events:
az container show --name mycontainer --resource-group myResourceGroup --query events
Common issues include image pull failures (due to registry authentication mismatches) and resource exhaustion. Use the az container show with --query instanceView.currentState to see the exit code and reason.
For deeper diagnostics, enable Container Insights. This provides CPU/memory per container and live logs streamed to Azure Monitor. You can also set up alerts on metrics like CPU percentage above 80% for proactive monitoring.
Conclusion
Azure Container Instances offers a fast, flexible, and cost-effective way to run Docker containers in the cloud without managing servers. From simple one-off tasks to production-adjacent workloads, ACI simplifies deployment while providing essential features like VNet integration, managed identities, and persistent storage. Combined with Azure Container Registry and Azure Monitor, it becomes a powerful component of a modern cloud-native architecture.
To take your container deployments further, explore integrating ACI with Azure DevOps pipelines for CI/CD, or combine it with AKS Virtual Nodes for burst capacity. For production use, always apply security best practices and regularly review cost usage.
By mastering ACI, you gain the ability to deploy containerized applications in minutes, with the confidence that your infrastructure can scale to meet demand without operational overhead.