Create your first function hosted on Linux using Core Tools and the Azure CLI (preview)

Azure Functions lets you execute your code in a serverless Linux environment without having to first create a VM or publish a web application. Linux-hosting is currently in preview and requires the Functions 2.0 runtime. To learn more about preview considerations for running your function apps on Linux, see this Functions on Linux article.

This quickstart article walks you through how to use the Azure CLI to create your first function app running on Linux. The function code is created locally and then deployed to Azure by using the Azure Functions Core Tools.

The following steps are supported on a Mac, Windows, or Linux computer. This article shows you how to create functions in either JavaScript or C#. To learn how to create Python functions, see Create your first Python function using Core Tools and the Azure CLI (preview).

Prerequisites

Before running this sample, you must have the following:

If you don't have an Azure subscription, create a free account before you begin.

Create the local function app project

Run the following command from the command line to create a function app project in the MyFunctionProj folder of the current local directory. A GitHub repo is also created in MyFunctionProj.

func init MyFunctionProj

When prompted, use the arrow keys to select a worker runtime from the following language choices:

  • dotnet: creates a .NET class library project (.csproj).
  • node: creates a JavaScript project.
  • python: creates a Python project. For Python functions, see the Python quickstart.

When the command executes, you see something like the following output:

Writing .gitignore
Writing host.json
Writing local.settings.json
Initialized empty Git repository in C:/functions/MyFunctionProj/.git/

Create a function

The following command creates an HTTP-triggered function named MyHtpTrigger.

func new --name MyHttpTrigger --template "HttpTrigger"

When the command executes, you see something like the following output:

The function "MyHttpTrigger" was created successfully from the "HttpTrigger" template.

Update the function

By default, the template creates a function that requires a function key when making requests. To make it easier to test the function in Azure, you need to update the function to allow anonymous access. The way that you make this change depends on your functions project language.

C#

Open the MyHttpTrigger.cs code file that is your new function and update the AuthorizationLevel attribute in the function definition to a value of anonymous and save your changes.

[FunctionName("MyHttpTrigger")]
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, 
            "get", "post", Route = null)]HttpRequest req, ILogger log)

JavaScript

Open the function.json file for your new function, open it in a text editor, update the authLevel property in bindings.httpTrigger to anonymous, and save your changes.

  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ]

Now you can call the function in Azure without having to supply the function key. The function key is never required when running locally.

Run the function locally

The following command starts the function app. The app runs using the same Azure Functions runtime that is in Azure.

func host start --build

The --build option is required to compile C# projects. You don't need this option for a JavaScript project.

When the Functions host starts, it write something like the following output, which has been truncated for readability:


                  %%%%%%
                 %%%%%%
            @   %%%%%%    @
          @@   %%%%%%      @@
       @@@    %%%%%%%%%%%    @@@
     @@      %%%%%%%%%%        @@
       @@         %%%%       @@
         @@      %%%       @@
           @@    %%      @@
                %%
                %

...

Content root path: C:\functions\MyFunctionProj
Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.

...

Http Functions:

        HttpTrigger: http://localhost:7071/api/MyHttpTrigger

[8/27/2018 10:38:27 PM] Host started (29486ms)
[8/27/2018 10:38:27 PM] Job host started

Copy the URL of your HttpTrigger function from the runtime output and paste it into your browser's address bar. Append the query string ?name=<yourname> to this URL and execute the request. The following shows the response in the browser to the GET request returned by the local function:

Test locally in the browser

Now that you have run your function locally, you can create the function app and other required resources in Azure.

Create a resource group

Create a resource group with the az group create. An Azure resource group is a logical container into which Azure resources like function apps, databases, and storage accounts are deployed and managed.

The following example creates a resource group named myResourceGroup.
If you are not using Cloud Shell, sign in first using az login.

az group create --name myResourceGroup --location westeurope

You generally create your resource group and the resources in a region near you. To see all supported locations for App Service plans, run the az appservice list-locations command.

Create an Azure Storage account

Functions uses a general-purpose account in Azure Storage to maintain state and other information about your functions. Create a general-purpose storage account in the resource group you created by using the az storage account create command.

In the following command, substitute a globally unique storage account name where you see the <storage_name> placeholder. Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only.

az storage account create --name <storage_name> --location westeurope --resource-group myResourceGroup --sku Standard_LRS

After the storage account has been created, the Azure CLI shows information similar to the following example:

{
  "creationTime": "2017-04-15T17:14:39.320307+00:00",
  "id": "/subscriptions/bbbef702-e769-477b-9f16-bc4d3aa97387/resourceGroups/myresourcegroup/...",
  "kind": "Storage",
  "location": "westeurope",
  "name": "myfunctionappstorage",
  "primaryEndpoints": {
    "blob": "https://myfunctionappstorage.blob.core.windows.net/",
    "file": "https://myfunctionappstorage.file.core.windows.net/",
    "queue": "https://myfunctionappstorage.queue.core.windows.net/",
    "table": "https://myfunctionappstorage.table.core.windows.net/"
  },
     ....
    // Remaining output has been truncated for readability.
}

Create a Linux App Service plan

In the Cloud Shell, create an App Service plan in the resource group with the az appservice plan create command.

The following example creates an App Service plan named myAppServicePlan in the Basic pricing tier (--sku B1) and in a Linux container (--is-linux).

az appservice plan create --name myAppServicePlan --resource-group myResourceGroup --sku B1 --is-linux

When the App Service plan has been created, the Azure CLI shows information similar to the following example:

{ 
  "adminSiteName": null,
  "appServicePlanName": "myAppServicePlan",
  "geoRegion": "West Europe",
  "hostingEnvironmentProfile": null,
  "id": "/subscriptions/0000-0000/resourceGroups/myResourceGroup/providers/Microsoft.Web/serverfarms/myAppServicePlan",
  "kind": "linux",
  "location": "West Europe",
  "maximumNumberOfWorkers": 1,
  "name": "myAppServicePlan",
  < JSON data removed for brevity. >
  "targetWorkerSizeId": 0,
  "type": "Microsoft.Web/serverfarms",
  "workerTierName": null
} 

Create a Linux function app in Azure

You must have a function app to host the execution of your functions on Linux. The function app provides a serverless environment for executing your function code. It lets you group functions as a logic unit for easier management, deployment, and sharing of resources. Create a function app running on Linux by using the az functionapp create command.

In the following command, use a unique function app name where you see the <app_name> placeholder and the storage account name for <storage_name>. The <app_name> is also the default DNS domain for the function app. This name needs to be unique across all apps in Azure. You should also set the <language> runtime for your function app, from dotnet (C#), node (JavaScript), or python.

az functionapp create --resource-group myResourceGroup --consumption-plan-location westus --os-type Linux \
--name <app_name> --storage-account  <storage_name> --runtime <language>

Note

If you have an existing resource group named myResourceGroup with any non-Linux App Service apps, you must use a different resource group. You can't host both Windows and Linux apps in the same resource group.

After the function app has been created, you see the following message:

Your serverless Linux function app 'myfunctionapp' has been successfully created.
To active this function app, publish your app content using Azure Functions Core Tools or the Azure portal.

Now, you can publish your project to the new function app in Azure.

Deploy the function app project to Azure

After the function app is created in Azure, you can use the func azure functionapp publish command to deploy your project code to Azure.

func azure functionapp publish <FunctionAppName>

You see something like the following output, which has been truncated for readability.

Getting site publishing info...

...

Preparing archive...
Uploading content...
Upload completed successfully.
Deployment completed successfully.
Syncing triggers...

You can now test your functions in Azure.

Test the function

Use cURL to test the deployed function on a Mac or Linux computer or using Bash on Windows. Execute the following cURL command, replacing the <app_name> placeholder with the name of your function app. Append the query string &name=<yourname> to the URL.

curl https://<app_name>.azurewebsites.net/api/MyHttpTrigger?name=<yourname>

Function response shown in a browser.

If you don't have cURL available in your command line, enter the same URL in the address of your web browser. Again, replace the <app_name> placeholder with the name of your function app, and append the query string &name=<yourname> to the URL and execute the request.

https://<app_name>.azurewebsites.net/api/MyHttpTrigger?name=<yourname>

Function response shown in a browser.

Clean up resources

Other quickstarts in this collection build upon this quickstart. If you plan to continue on to work with subsequent quickstarts or with the tutorials, do not clean up the resources created in this quickstart. If you do not plan to continue, use the following command to delete all resources created by this quickstart:

az group delete --name myResourceGroup

Type y when prompted.

Next steps

This article showed you how to host your function app on a default Azure App Service container. You can also host your functions on Linux in your own custom container.