Azure function with docker
Install func cli
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
- Add required packages
dotnet add package Microsoft.Azure.Functions.Extensions
dotnet add package Microsoft.NET.Sdk.Functions
- Make the function class and methods not static and inject
IConfiguration
in the constructor
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:
- The port mapping is for the http endpoint to be visible from the host (vagrant VM).
- The application settings need to be set as environment variables for the, e.g. a connection string or any. (secrets would need to be in the keyvault in a production scenario, though)
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
- Both locally and in Azure, the appsettings need to be set as environment variables.
- In the case of HttpEndpoint, by default (
Route=null
) the url isapi/<FUNCTION_NAME>
. If route setRoute="health"
, the url isapi/health
.