Deploying Azure Functions in Containers to Azure Container Apps - like a boss!!!
Introduction
In today's cloud-native world, containerization has become a fundamental approach for deploying applications. Azure Functions can be containerized and deployed to a docker container which means we can deploy them on kubernetes. One compelling option is Azure Container Apps (ACA), which provides a fully managed Kubernetes-based environment with powerful features specifically designed for microservices and containerized applications.
Azure Container Apps is powered by Kubernetes and open-source technologies like Dapr, KEDA, and Envoy. It supports Kubernetes-style apps and microservices with features like service discovery and traffic splitting while enabling event-driven application architectures. This makes it an excellent choice for deploying containerized Azure Functions.
This blog post explores how to deploy Azure Functions in containers to Azure Container Apps, with special focus on the benefits of Envoy for traffic management, revision handling, and logging capabilities for troubleshooting.
Video Demo:
Why Deploy Azure Functions to Container Apps?
Container Apps hosting lets you run your functions in a fully managed, Kubernetes-based environment with built-in support for open-source monitoring, mTLS, Dapr, and Kubernetes Event-driven Autoscaling (KEDA). You can write your function code in any language stack supported by Functions and use the same Functions triggers and bindings with event-driven scaling.
Key advantages include:
- Containerization flexibility: Package your functions with custom dependencies and runtime environments for Dev, QA, STG and PROD
- Kubernetes-based infrastructure: Get the benefits of Kubernetes without managing the complexity
- Microservices architecture support: Deploy functions as part of a larger microservices ecosystem
- Advanced networking: Take advantage of virtual network integration and service discovery
Benefits of Envoy in Azure Container Apps
Azure Container Apps includes a built-in Ingress controller running Envoy. You can use this to expose your application to the outside world and automatically get a URL and an SSL certificate. Envoy brings several significant benefits to your containerized Azure Functions:
1. Advanced Traffic Management
Envoy serves as the backbone of ACA's traffic management capabilities, allowing for:
- Intelligent routing: Route traffic based on paths, headers, and other request attributes
- Load balancing: Distribute traffic efficiently across multiple instances
- Protocol support: Downstream connections support HTTP1.1 and HTTP2, and Envoy automatically detects and upgrades connections if the client connection requires an upgrade.
2. Built-in Security
- TLS termination: Automatic handling of HTTPS traffic with Azure managed certificates
- mTLS support: Azure Container Apps supports peer-to-peer TLS encryption within the environment. Enabling this feature encrypts all network traffic within the environment with a private certificate that is valid within the Azure Container Apps environment scope. Azure Container Apps automatically manage these certificates.
3. Observability
- Detailed metrics and logs for traffic patterns
- Request tracing capabilities
- Performance insights for troubleshooting
Traffic Management for Revisions
One of the most powerful features of Azure Container Apps is its handling of revisions and traffic management between them.
Understanding Revisions
Revisions are immutable snapshots of your container application at a point in time. When you upgrade your container app to a new version, you create a new revision. This allows you to have the old and new versions running simultaneously and use the traffic management functionality to direct traffic to old or new versions of the application.
Traffic Splitting Between Revisions
Traffic split is a mechanism that routes configurable percentages of incoming requests (traffic) to various downstream services. With Azure Container Apps, we can weight traffic between multiple downstream revisions.
This capability enables several powerful deployment strategies:
Blue/Green Deployments
Deploy a new version alongside the existing one, and gradually shift traffic:
- Deploy revision 2 (green) alongside revision 1 (blue)
- Initially direct a small percentage (e.g., 10%) of traffic to revision 2
- Monitor performance and errors
- Gradually increase traffic to revision 2 as confidence grows
- Eventually direct 100% traffic to revision 2
- Retire revision 1 when no longer needed
A/B Testing
Test different implementations with real users:
Traffic splitting is useful for testing updates to your container app. You can use traffic splitting to gradually phase in a new revision in blue-green deployments or in A/B testing. Traffic splitting is based on the weight (percentage) of traffic that is routed to each revision.
Implementation
To implement traffic splitting in Azure Container Apps:
By default, when ingress is enabled, all traffic is routed to the latest deployed revision. When you enable multiple revision mode in your container app, you can split incoming traffic between active revisions.
Here's how to configure it:
- Enable multiple revision mode:
- In the Azure portal, go to your container app
- Select "Revision management"
- Set the mode to "Multiple: Several revisions active simultaneously"
- Apply changes
- Configure traffic weights:
- For each active revision, specify the percentage of traffic it should receive
- Ensure the combined percentage equals 100%
Logging and Troubleshooting
Effective logging is crucial for monitoring and troubleshooting containerized applications. Azure Container Apps provides comprehensive logging capabilities integrated with Azure Monitor.
Centralized Logging Infrastructure
Azure Container Apps environments provide centralized logging capabilities through integration with Azure Monitor and Application Insights. By default, all container apps within an environment send logs to a common Log Analytics workspace, making it easier to query and analyze logs across multiple apps.
Key Logging Benefits
- Unified logging experience: All container apps in an environment send logs to the same workspace
- Detailed container insights: Access container-specific metrics and logs
- Function-specific logging: You can monitor your containerized function app hosted in Container Apps using Azure Monitor Application Insights in the same way you do with apps hosted by Azure Functions.
- Scale event logging: For bindings that support event-driven scaling, scale events are logged as FunctionsScalerInfo and FunctionsScalerError events in your Log Analytics workspace.
Troubleshooting Best Practices
When troubleshooting issues in containerized Azure Functions running on ACA:
- Check application logs: Review function execution logs for errors or exceptions
- Monitor scale events: Identify issues with auto-scaling behavior
- Examine container health: Check for container startup failures or crashes
- Review ingress traffic: Analyze traffic patterns and routing decisions
- Inspect revisions: Verify that traffic is being distributed as expected between revisions
Implementation Steps
Here's the full playlist we did in youtube to follow along: https://www.youtube.com/playlist?list=PLKwr1he0x0Dl2glbE8oHeTgdY-_wZkrhi
In Summary:
- Containerize your Azure Functions app:
- Create a Dockerfile based on the Azure Functions base images
- Build and test your container locally
- Video demo:
- Push your container to a registry:
- Push to Azure Container Registry or another compatible registry
- Create a Container Apps environment:
- Set up the environment with appropriate virtual network and logging settings
- Deploy your function container:
- Use Azure CLI, ARM templates, or the Azure Portal to deploy
- Configure scaling rules, ingress settings, and revision strategy
- Set up traffic management:
- Enable multiple revision mode if desired
- Configure traffic splitting rules for testing or gradual rollout
Conclusion
Deploying Azure Functions in containers to Azure Container Apps combines the best of serverless computing with the flexibility of containers and the rich features of a managed Kubernetes environment. The built-in Envoy proxy provides powerful traffic management capabilities, especially for handling multiple revisions of your application. Meanwhile, the integrated logging infrastructure simplifies monitoring and troubleshooting across all your containerized functions.
This approach is particularly valuable for teams looking to:
- Deploy Azure Functions with custom dependencies
- Integrate functions into a microservices architecture
- Implement sophisticated deployment strategies like blue/green or A/B testing
- Maintain a consistent container-based deployment strategy across all application components
By leveraging these capabilities, you can create more robust, scalable, and manageable serverless applications while maintaining the development simplicity that makes Azure Functions so powerful.
Azure Container Apps: Simplifying Container Deployment with Enterprise-Grade Features
In the ever-evolving landscape of cloud computing, organizations are constantly seeking solutions that balance simplicity with enterprise-grade capabilities. Azure Container Apps emerges as a compelling answer to this challenge, offering a powerful abstraction layer over container orchestration while providing the robustness needed for production workloads.
What Makes Azure Container Apps Special?
Azure Container Apps represents Microsoft’s vision for serverless container deployment. While Kubernetes has become the de facto standard for container orchestration, its complexity can be overwhelming for teams that simply want to deploy and scale their containerized applications. Container Apps provides a higher-level abstraction that handles many infrastructure concerns automatically, allowing developers to focus on their applications.
Key Benefits of the Platform
Built-in Load Balancing with Envoy
One of the standout features of Azure Container Apps is its integration with Envoy as a load balancer. This isn’t just any load balancer – Envoy is the same battle-tested proxy used by major cloud-native platforms. It provides:
- Automatic HTTP/2 and gRPC support
- Advanced traffic splitting capabilities for A/B testing
- Built-in circuit breaking and retry logic
- Detailed metrics and tracing
The best part? You don’t need to configure or maintain Envoy yourself. It’s managed entirely by the platform, giving you enterprise-grade load balancing capabilities without the operational overhead.
Integrated Observability with Azure Application Insights
Understanding what’s happening in your containerized applications is crucial for maintaining reliability. Container Apps integrates seamlessly with Azure Application Insights, providing:
- Distributed tracing across your microservices
- Detailed performance metrics and request logging
- Custom metric collection
- Real-time application map visualization
The platform automatically injects the necessary instrumentation, ensuring you have visibility into your applications from day one.
Cost Considerations and Optimization
While Azure Container Apps offers a serverless pricing model that can be cost-effective, it’s important to understand the pricing structure to avoid surprises:
Cost Components
- Compute Usage: Charged per vCPU-second and GB-second of memory used
- Baseline: ~$0.000012/vCPU-second
- Memory: ~$0.000002/GB-second
- Request Processing:
- First 2 million requests/month included
- ~$0.40 per additional million requests
- Storage and Networking:
- Ingress: Free
- Egress: Standard Azure bandwidth rates apply
Cost Optimization Tips
To keep your Azure Container Apps costs under control:
- Right-size your containers by carefully setting resource limits and requests
- Utilize scale-to-zero for non-critical workloads
- Configure appropriate minimum and maximum replica counts
- Monitor and adjust based on actual usage patterns
Advanced Features Worth Exploring
Revision Management
Container Apps introduces a powerful revision management system that allows you to:
- Maintain multiple versions of your application
- Implement blue-green deployments
- Roll back to previous versions if needed
DAPR Integration
For microservices architectures, the built-in DAPR (Distributed Application Runtime) support provides:
- Service-to-service invocation
- State management
- Pub/sub messaging
- Input and output bindings
Conclusion
Azure Container Apps strikes an impressive balance between simplicity and capability. It removes much of the complexity associated with container orchestration while providing the features needed for production-grade applications. Whether you’re building microservices, web applications, or background processing jobs, Container Apps offers a compelling platform that can grow with your needs.
By understanding the pricing model and following best practices for cost optimization, you can leverage this powerful platform while keeping expenses under control. The integration with Azure’s broader ecosystem, particularly Application Insights and Container Registry, creates a seamless experience for developing, deploying, and monitoring containerized applications.
Remember to adjust resource allocations and scaling rules based on your specific workload patterns to optimize both performance and cost. Monitor your application’s metrics through Application Insights to make informed decisions about resource utilization and scaling policies.
🚀 Mastering Azure Functions in Docker: Secure Your App with Function Keys! 🔒
In this session, we’re merging the robust capabilities of Azure Functions with the versatility of Docker containers.
By the end of this tutorial, you will have a secure and scalable process for deploying your Azure Functions within Docker, equipped with function keys to ensure security.
Why use Azure Functions inside Docker?
Serverless architecture allows you to run code without provisioning or managing servers. Azure Functions take this concept further by providing a fully managed compute platform. Docker, on the other hand, offers a consistent development environment, making it easy to deploy your applications across various environments. Together, they create a robust and efficient way to develop and deploy serverless applications. Later we will be deploy this container to our local kubernetes cluster and to Azure Container Apps.
Development
The Azure Functions Core tools make it easy to package your function into a container with a single command:
func init MyFunctionApp --docker
The command creates the dockerfile and supporting json for your function inside a container and all you need to do is add your code and dependencies. Since we are building a python function we will be adding our python libraries in the requirements.txt
Using Function Keys for Security
Create a host_secret.json
file in the root of your function app directory. Add the following configuration to specify your function key:
{
"masterKey": {
"name": "master",
"value": "your-master-key-here"
},
"functionKeys": {
"default": "your-function-key-here"
}
}
Now this file needs to be added to the container so the function can read it. You can simply add the following to your dockerfile and rebuild:
RUN mkdir /etc/secrets/
ENV FUNCTIONS_SECRETS_PATH=/etc/secrets
ENV AzureWebJobsSecretStorageType=Files
ENV PYTHONHTTPSVERIFY=0
ADD host_secrets.json /etc/secrets/host.json
Testing
Now you can use the function key you set in the previous step as a query parameter for the function’s endpoint in your api client.
Or you can use curl / powershell as well:
curl -X POST \
'http://192.168.1.200:8081/api/getbooks?code=XXXX000something0000XXXX' \
--header 'Accept: */*' \
--header 'User-Agent: Thunder Client (https://www.thunderclient.com)' \
--header 'Content-Type: application/json' \
--data-raw '{
"query": "Dune"
}'
Django Microservices Approach with Azure Functions on Azure Container Apps
We are creating a multi-part video to explain Azure Functions running on Azure Container Apps so that we can offload some of the code out of our Django App and build our infrastructure with a microservice approach. Here’s part one and below the video a quick high-level explanation for this architecture.
Azure Functions are serverless computing units within Azure that allow you to run event-driven code without having to manage servers. They’re a great choice for building microservices due to their scalability, flexibility, and cost-effectiveness.
Azure Container Apps provide a fully managed platform for deploying and managing containerized applications. By deploying Azure Functions as containerized applications on Container Apps, you gain several advantages:
-
Microservices Architecture:
- Decoupling: Each function becomes an independent microservice, isolated from other parts of your application. This makes it easier to develop, test, and deploy them independently.
- Scalability: You can scale each function individually based on its workload, ensuring optimal resource utilization.
- Resilience: If one microservice fails, the others can continue to operate, improving the overall reliability of your application.
-
Containerization:
- Portability: Containerized functions can be easily moved between environments (development, testing, production) without changes.
- Isolation: Each container runs in its own isolated environment, reducing the risk of conflicts between different functions.
- Efficiency: Containers are optimized for resource utilization, making them ideal for running functions on shared infrastructure.
-
Azure Container Apps Benefits:
- Managed Service: Azure Container Apps handles the underlying infrastructure, allowing you to focus on your application’s logic.
- Scalability: Container Apps automatically scale your functions based on demand, ensuring optimal performance.
- Integration: It seamlessly integrates with other Azure services, such as Azure Functions, Azure App Service, and Azure Kubernetes Service.
In summary, Azure Functions deployed on Azure Container Apps provide a powerful and flexible solution for building microservices. By leveraging the benefits of serverless computing, containerization, and a managed platform, you can create scalable, resilient, and efficient applications.