Lưu ý
Cần có ủy quyền mới truy nhập được vào trang này. Bạn có thể thử đăng nhập hoặc thay đổi thư mục.
Cần có ủy quyền mới truy nhập được vào trang này. Bạn có thể thử thay đổi thư mục.
Azure Container Apps jobs enable you to run containerized tasks that run for a finite duration and then stop. You can trigger a job execution manually, on a schedule, or based on events. Jobs are best suited to for tasks such as data processing, machine learning, resource cleanup, or any scenario that requires serverless ephemeral compute resources.
In this tutorial, you learn how to work with event-driven jobs.
- Create a Container Apps environment in which to deploy your container apps
- Create an Azure Storage queue to send messages to the container app
- Build a container image that runs a job
- Deploy the job to the Container Apps environment
- Verify that the queue messages are processed by the container app
The job you create starts an execution for each message that's sent to an Azure Storage queue. Each job execution runs a container that performs the following steps:
- Gets one message from the queue.
- Logs the message to the job execution logs.
- Deletes the message from the queue.
- Stops.
Important
The scaler monitors the queue's length to determine how many jobs to start. For accurate scaling, don't delete a message from the queue until the job execution finishes processing it.
The source code for the job you run in this tutorial is available in an Azure Samples GitHub repository.
Prerequisites
- An Azure account with an active subscription. If you don't have one, you can create one for free.
- The Azure CLI.
For information about features that Container Apps jobs don't support, see Jobs restrictions.
Prepare the environment
To sign in to Azure from the Azure CLI, run the following command and follow the prompts to complete the authentication process.
az loginEnsure you're running the latest version of the Azure CLI via the
az upgradecommand.az upgradeInstall the latest version of the Container Apps CLI extension.
az extension add --name containerapp --upgradeRegister the
Microsoft.App,Microsoft.OperationalInsights, andMicrosoft.Storagenamespaces if they aren't already registered in your Azure subscription.az provider register --namespace Microsoft.App az provider register --namespace Microsoft.OperationalInsights az provider register --namespace Microsoft.StorageDefine the environment variables that are used throughout this article.
RESOURCE_GROUP="jobs-quickstart" LOCATION="northcentralus" ENVIRONMENT="env-jobs-quickstart" JOB_NAME="my-job"
Create a Container Apps environment
The Container Apps environment acts as an isolation boundary around container apps and jobs so they can share the same network and communicate with each other.
Create a resource group by using the following command.
az group create \ --name "$RESOURCE_GROUP" \ --location "$LOCATION"Create the Container Apps environment by using the following command.
az containerapp env create \ --name "$ENVIRONMENT" \ --resource-group "$RESOURCE_GROUP" \ --location "$LOCATION"
Set up a storage queue
The job uses an Azure Storage queue to receive messages. In this section, you create a storage account and a queue.
Define a name for your storage account.
STORAGE_ACCOUNT_NAME="<STORAGE_ACCOUNT_NAME>" QUEUE_NAME="myqueue"Replace
<STORAGE_ACCOUNT_NAME>with a unique name for your storage account. Storage account names must be unique within Azure. They must be between 3 and 24 characters long and contain numbers and lowercase letters only.Create an Azure Storage account.
az storage account create \ --name "$STORAGE_ACCOUNT_NAME" \ --resource-group "$RESOURCE_GROUP" \ --location "$LOCATION" \ --sku Standard_LRS \ --kind StorageV2If this command returns the following error, be sure you have registered the
Microsoft.Storagenamespace in your Azure subscription.(SubscriptionNotFound) Subscription <SUBSCRIPTION_ID> was not found. Code: SubscriptionNotFound Message: Subscription <SUBSCRIPTION_ID> was not found.Use this command to register the namespace:
az provider register --namespace Microsoft.StorageSave the queue's connection string into a variable:
QUEUE_CONNECTION_STRING=$(az storage account show-connection-string -g $RESOURCE_GROUP --name $STORAGE_ACCOUNT_NAME --query connectionString --output tsv)Create the message queue:
az storage queue create \ --name "$QUEUE_NAME" \ --account-name "$STORAGE_ACCOUNT_NAME" \ --connection-string "$QUEUE_CONNECTION_STRING"
Create a user-assigned managed identity
To avoid using administrative credentials, pull images from private repositories in Azure Container Registry. Use managed identities for authentication. When possible, use a user-assigned managed identity to pull images.
Create a user-assigned managed identity. Before you run the following commands, choose a name for your managed identity and create the following variable:
IDENTITY="<YOUR_IDENTITY_NAME>"az identity create \ --name $IDENTITY \ --resource-group $RESOURCE_GROUPGet the identity's resource ID:
IDENTITY_ID=$(az identity show \ --name $IDENTITY \ --resource-group $RESOURCE_GROUP \ --query id \ --output tsv)
Build and deploy the job
To deploy the job, you must first build a container image for it and push the container to a registry. You can then deploy the job to the Container Apps environment.
Define a name for your container image and registry:
CONTAINER_IMAGE_NAME="queue-reader-job:1.0" CONTAINER_REGISTRY_NAME="<CONTAINER_REGISTRY_NAME>"Replace
<CONTAINER_REGISTRY_NAME>with a unique name for your container registry. Container registry names must be unique within Azure. They must be between 5 and 50 characters long and contain numbers and lowercase letters only.Create a container registry:
az acr create \ --name "$CONTAINER_REGISTRY_NAME" \ --resource-group "$RESOURCE_GROUP" \ --location "$LOCATION" \ --sku BasicYour container registry must allow Azure Resource Manager (ARM) audience tokens for authentication in order to use managed identity to pull images.
Use the following command to check whether ARM tokens are allowed to access your Azure container registry:
az acr config authentication-as-arm show --registry "$CONTAINER_REGISTRY_NAME"If ARM tokens are allowed, you see the following output:
{ "status": "enabled" }If the
statusisdisabled, allow ARM tokens by using the following command:az acr config authentication-as-arm update --registry "$CONTAINER_REGISTRY_NAME" --status enabledThe source code for the job is available on GitHub. Run the following command to clone the repository and build the container image in the cloud:
az acr build \ --registry "$CONTAINER_REGISTRY_NAME" \ --image "$CONTAINER_IMAGE_NAME" \ "https://github.com/Azure-Samples/container-apps-event-driven-jobs-tutorial.git"The image is now available in the container registry.
Create a job in the Container Apps environment:
az containerapp job create \ --name "$JOB_NAME" \ --resource-group "$RESOURCE_GROUP" \ --environment "$ENVIRONMENT" \ --trigger-type "Event" \ --replica-timeout "1800" \ --min-executions "0" \ --max-executions "10" \ --polling-interval "60" \ --scale-rule-name "queue" \ --scale-rule-type "azure-queue" \ --scale-rule-metadata "accountName=$STORAGE_ACCOUNT_NAME" "queueName=$QUEUE_NAME" "queueLength=1" \ --scale-rule-auth "connection=connection-string-secret" \ --image "$CONTAINER_REGISTRY_NAME.azurecr.io/$CONTAINER_IMAGE_NAME" \ --cpu "0.5" \ --memory "1Gi" \ --secrets "connection-string-secret=$QUEUE_CONNECTION_STRING" \ --registry-server "$CONTAINER_REGISTRY_NAME.azurecr.io" \ --mi-user-assigned "$IDENTITY_ID" \ --registry-identity "$IDENTITY_ID" \ --env-vars "AZURE_STORAGE_QUEUE_NAME=$QUEUE_NAME" "AZURE_STORAGE_CONNECTION_STRING=secretref:connection-string-secret"The following table describes the key parameters used in the previous command.
Parameter Description --replica-timeoutThe maximum duration a replica can run. --min-executionsThe minimum number of job executions to run per polling interval. --max-executionsThe maximum number of job executions to run per polling interval. --polling-intervalThe polling interval at which to evaluate the scale rule. --scale-rule-nameThe name of the scale rule. --scale-rule-typeThe type of scale rule to use. --scale-rule-metadataThe metadata for the scale rule. --scale-rule-authThe authentication for the scale rule. --secretsThe secrets to use for the job. --registry-serverThe container registry server to use for the job. For an Azure container registry, the command automatically configures authentication. --mi-user-assignedThe resource ID of the user-assigned managed identity to assign to the job. --registry-identityThe resource ID of a managed identity to authenticate with the registry server instead of using a user name and password. If possible, an acrpullrole assignment is automatically created for the identity.--env-varsThe environment variables to use for the job. The scale rule configuration defines the event source to monitor. It's evaluated on each polling interval and determines how many job executions to trigger. For more information, see Set scaling rules.
The event-driven job is now created in the Container Apps environment.
Verify the deployment
The job is configured to evaluate the scale rule every 60 seconds. This evaluation checks the number of messages in the queue. For each evaluation period, it starts a new job execution for each message in the queue, up to a maximum of 10 executions.
To verify that the job is configured correctly, you can send some messages to the queue and confirm that job executions are started and that the messages are logged to the job execution logs.
Send a message to the queue:
az storage message put \ --content "Hello Queue Reader Job" \ --queue-name "$QUEUE_NAME" \ --connection-string "$QUEUE_CONNECTION_STRING"List the executions of a job:
az containerapp job execution list \ --name "$JOB_NAME" \ --resource-group "$RESOURCE_GROUP" \ --output jsonBecause the job is configured to evaluate the scale rule every 60 seconds, it might take up to a full minute for the job execution to start. Repeat the command until you see the job execution and its status is
Succeeded.Run the following commands to see logged messages. These commands require the Log analytics extension, so accept the prompt to install the extension.
LOG_ANALYTICS_WORKSPACE_ID=$(az containerapp env show --name $ENVIRONMENT --resource-group $RESOURCE_GROUP --query properties.appLogsConfiguration.logAnalyticsConfiguration.customerId --output tsv) az monitor log-analytics query \ --workspace "$LOG_ANALYTICS_WORKSPACE_ID" \ --analytics-query "ContainerAppConsoleLogs_CL | where ContainerJobName_s == '$JOB_NAME' | order by _timestamp_d asc"Until the
ContainerAppConsoleLogs_CLtable is ready, the command returns an error:BadArgumentError: The request had some invalid properties. Wait a few minutes and try again.
Tip
Having problems? Let us know on GitHub by opening an issue in the Azure Container Apps repo.
Clean up resources
When you're done, run the following command to delete the resource group that contains your Container Apps resources.
Caution
The following command deletes the specified resource group and all resources contained in it. If there are resources outside the scope of this tutorial in the specified resource group, they're also deleted.
az group delete \
--resource-group $RESOURCE_GROUP