简体   繁体   中英

Start and stop Docker container from Azure function based on input

I was wondering if there is some way that one can achieve the following on the Azure cloud platform:

  1. Start a Docker container (Azure Container Instances) from an Azure function with C# code based on input parameters and file posted to the Azure function.

  2. After the container has been started, a software inside the container has to be started to do some work based on the input file and parameters that was posted to the Azure function.

  3. After the software inside the Docker container is done, and written the output to some database (MS SQL Server also in Azure), the Azure function must stop the container (could also be a different Azure function that polls, for example once every minute, to check if no work is being done by any Docker image).

  4. If there are requests coming to the Azure function while a Docker container currently is up and running, the functions spins a new Docker container up from the same image and does the same ting.

The reason for the need to start and stopping the Docker container is to keep the cost down because of the demanding work load that needs an instance that uses multiple CPU cores and a lot of RAM.

In your Function, you can start and stop containers in ACI using the Microsoft.Azure.Management.ContainerInstance Namespace in C#. Here's a link to the Nuget package and a sample I found:

var containerGroup = azure.ContainerGroups.Define(containerGroupName)
    .WithRegion(azureRegion)
    .WithExistingResourceGroup(resourceGroupName)
    .WithLinux()
    .WithPublicImageRegistryOnly()
    .WithoutVolume()
    .DefineContainerInstance(containerGroupName)
         .WithImage(containerImage)
         .WithExternalTcpPort(80)
         .WithCpuCoreCount(1.0)
         .WithMemorySizeInGB(1)
         .Attach()
    .WithDnsPrefix(containerGroupName)
    .Create();

There are many ways to achieve your goal. Instead of using Functions, you can use Logic App to start and stop containers in ACI using the ACI connector . You could think of a workflow similar to this:

  • Add an action that will trigger the Logic App like a new message in a queue.
  • Create an ACI container group using the connector.
  • Launch a container in ACI using the connector.
  • You watch the container state to see if it was created successfully.
  • You can pass values to the container by setting env variables using the ACI connector like a file name or a job number.
  • You add a loop that watch for completion of your code in the container (output that you send in the log)
  • You delete the ACI using the connector

You can of course run multiple Logic Apps in parallel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM