Azure function with docker

Install func cli

https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Ccsharp%2Cbash#install-the-azure-functions-core-tools

Create function project

func init Bustroker.HttpEndpoint.Func --dotnet --docker

I renamed csproj file from Bustroker_HttpEndpoint_Func.csproj to Bustroker.HttpEndpoint.Func.csproj. The docker file is created. No need for docker to be installed. I run docker in Ubuntu VM, with Vagrant.

Create function

cd Bustroker.HttpEndpoint.Func
func new --name HttpEndpoint [--template {HttpTrigger, CosmosDbTrigger, etc}]

App settings

dotnet add package Microsoft.Azure.Functions.Extensions
dotnet add package Microsoft.NET.Sdk.Functions
namespace Bustroker.HttpEndpoint.Func
{
    public class HttpEndpoint
    {
        private readonly IConfiguration _configuration;

        public HttpEndpoint(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [FunctionName("HttpEndpoint")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "config")] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            var setting = req.Query["setting"];
            var value = _configuration.GetValue<string>(setting);
            var response = await Task.FromResult($"setting: {setting}; value:{value}");
            return new OkObjectResult(response);
        }
    }
}

The configuration is read from environment variables. So, run the container as

docker run -p 80:80 -e setting1=value1 -e setting2=value2 <IMAGE>:<TAG>

Services dependency injection

Create a Startup class

// Startup.cs
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(Arch.Pocs.Containers.AppService.HttpEndpoint.Func.Startup))]
namespace Arch.Pocs.Containers.AppService.HttpEndpoint.Func
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // e.g., for http client injection
            builder.Services.AddHttpClient();
        }
    }
}

Then just add it to the constructor of the function class (already not static).

Run locally

In my case, inside vagrant vm (my windows and docker don’t get along well). A couple remarks:

docker build -t function .
docker run -p 80:80 -e cosmosDbConnectionString="AccountEndpoint=https://bustroker-transactions-cosmosdb.documents.azure.com:443/;AccountKey=SUP3R4CC0UNTK3Y==;" function:latest

Remarks

Deploy