Deploy a Worker Service to Azure

In this article, you'll learn how to deploy a .NET Worker Service to Azure. With your Worker running as an Azure Container Instance (ACI) from the Azure Container Registry (ACR), it can act as a microservice in the cloud. There are many use cases for long-running services, and the Worker Service exists for this reason.

In this tutorial, you learn how to:

  • Create a worker service.
  • Create container registry resource.
  • Push an image to container registry.
  • Deploy as container instance.
  • Verify worker service functionality.

Tip

All of the "Workers in .NET" example source code is available in the Samples Browser for download. For more information, see Browse code samples: Workers in .NET.

Prerequisites

Create a new project

To create a new Worker Service project with Visual Studio, select File > New > Project.... From the Create a new project dialog search for "Worker Service", and select Worker Service template. Enter the desired project name, select an appropriate location, and select Next. On the Additional information page, for the Target Framework select .NET 5.0, and check the Enable Docker option to enable docker support. Select the desired Docker OS.

To create a new Worker Service project with Visual Studio Code, you can run .NET CLI commands from the integrated terminal. For more information, see Visual Studio Code: Integrated Terminal.

Open the integrated terminal, and run the dotnet new command, and replace the <Project.Name> with your desired project name.

dotnet new worker --name <Project.Name>

For more information on the .NET CLI new worker service project command, see dotnet new worker.

To create a new Worker Service project with the .NET CLI, open your favorite terminal in a working directory. Run the dotnet new command, and replace the <Project.Name> with your desired project name.

dotnet new worker --name <Project.Name>

For more information on the .NET CLI new worker service project command, see dotnet new worker.

Build the application to ensure it restores the dependent packages, and compiles without error.

To build the application from Visual Studio, select F6 or select the Build > Build Solution menu option.

To build the application from Visual Studio Code, open the integrated terminal window and run the dotnet build command from the working directory.

dotnet build

For more information on the .NET CLI build command, see dotnet build.

To build the application from the .NET CLI, run the dotnet build command from the working directory.

dotnet build <path/to/project.csproj>

Specify your <path/to/project.csproj> value, which is the path to the project file to build. For more information on the .NET CLI build command, see dotnet build.

Add Docker support

If you correctly selected the Enable Docker checkbox when creating a new Worker project, skip to the Build the Docker image step.

If you didn't select this option, no worries—you can still add it now. In Visual Studio, right-click on the project node in the Solution Explorer, and select Add > Docker Support. You'll be prompted to select a Target OS, select OK with the default OS selection.

Docker File Options

In Visual Studio Code, you'll need the Docker extension and the Azure Account extension installed. Open the Command Palette, and select the Docker: Add Docker files to workspace option. If prompted to Select Application Platform, choose .NET: Core Console. If prompted to Select Project, choose the Worker Service project you created. When prompted to Select Operating System, choose the first listed OS. When prompted whether or not to Include optional Docker Compose files, select No.

Docker support requires a Dockerfile. This file is a set of comprehensive instructions, for building your .NET Worker Service as a Docker image. The Dockerfile is a file without a file extension. The following is an example Dockerfile, and should exist at the root directory of the project file.

With the CLI, the Dockerfile is not created for you. You'll need to copy its contents into a new file name Dockerfile, and again this file should be in the root directory of the project.

FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base
WORKDIR /app

# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-dotnet-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["App.CloudService.csproj", "./"]
RUN dotnet restore "App.CloudService.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "App.CloudService.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "App.CloudService.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "App.CloudService.dll"]

Note

You need to update the various lines in the Dockerfile that reference *App.CloudService—replace this with the name of your project.

For more information on the official .NET images, see Docker Hub: .NET Runtime and Docker Hub: .NET SDK.

Build the Docker image

To build the Docker image, the Docker Engine must be running.

Important

When using Docker Desktop and Visual Studio, to avoid errors related to volume sharing — ensure that it is enabled.

  1. On the Settings screen in Docker Desktop, select Shared Drives.
  2. Select the drive(s) containing your project files.

For more information, see Troubleshoot Visual Studio development with Docker.

Right-click on the Dockerfile in the Solution Explorer, and select Build Docker Image. The Output window displays, reporting the docker build command progress.

Right-click on the Dockerfile in the Explorer, and select Build Image. When prompted to Tag image as, enter appcloudservice:latest. The Docker Task output terminal displays, reporting the Docker build command progress.

Note

If you're not prompted to tag the image, it's possible that Visual Studio Code is relying on an existing tasks.json. If the tag used is undesirable, you can change it by updating the docker-build configuration item's dockerBuild/tag value in the tasks array. Consider the following example configuration section:

{
  "type": "docker-build",
  "label": "docker-build: release",
  "dependsOn": [
    "build"
  ],
  "dockerBuild": {
    "tag": "appcloudservice:latest",
    "dockerfile": "${workspaceFolder}/cloud-service/Dockerfile",
    "context": "${workspaceFolder}",
    "pull": true
  },
  "netCore": {
    "appProject": "${workspaceFolder}/cloud-service/App.CloudService.csproj"
  }
}

Open a terminal window in the root directory of the Dockerfile, and run the following docker command:

docker build -t appcloudservice:latest -f Dockerfile .

As the docker build command runs, it processes each line in the Dockerfile as an instruction step. This command builds the image and creates a local repository named appcloudservice that points to the image.

Tip

The generated Dockerfile differs between development environments. For example, if you Add Docker support from Visual Studio you may experience issues if you attempt to Build the Docker image from Visual Studio Code — as the Dockerfile steps vary. It is best to choose a single development environment and use it through out this tutorial.

Create container registry

An Azure Container Registry (ACR) resource allows you to build, store, and manage container images and artifacts in a private registry. To create a container registry, you'll need to create a new resource in the Azure portal.

  1. Select the Subscription, and corresponding Resource group (or create a new one).
  2. Enter a Registry name.
  3. Select a Location.
  4. Select an appropriate SKU, for example Basic.
  5. Select Review + create.
  6. After seeing Validation passed, select Create.

Important

In order to use this container registry when creating a container instance, you must enable Admin user. Select Access keys, and enable Admin user.

An Azure Container Registry (ACR) resource allows you to build, store, and manage container images and artifacts in a private registry. Open a terminal window in the root directory of the Dockerfile, and run the following Azure CLI command:

Important

To interact with Azure resources from the Azure CLI, you must be authenticated for your terminal session. To authenticate, use the az login command:

az login

After you're logged in, use the az account set command to specify your subscription when you have more than one and no default subscription set.

az account set --subscription <subscription name or id>

Once you sign in to the Azure CLI, your session can interact with resources accordingly.

If you do not already have a resource group you'd like to associate your worker service with, create one using the az group create command:

az group create -n <resource group> -l <location>

Provide the <resource group> name, and the <location>. To create a container registry, you'll need to call the az acr create command.

az acr create -n <registry name> -g <resource group> --sku <sku> --admin-enabled true

Replace placeholders with your own appropriate values:

  • <registry name>: the name of the registry.
  • <resource group>: the resource group name that you used above.
  • <sku>: accepted values, Basic, Classic, Premium, or Standard.

The preceding command:

  • Creates an Azure Container Registry, given a registry name, in the specified resource group.
  • Enabled an Admin user—this is required for Azure Container Instances.

For more information, see Quickstart: Create an Azure container registry.

Push image to container registry

With the .NET Docker image built, and the container registry resource created, you can now push the image to container registry.

Right-click on the project in the Solution Explorer, and select Publish. The Publish dialog displays. For the Target, select Azure and then Next.

Visual Studio: Publish dialog - select Azure

For the Specific Target, select Azure Container Registry and then Next.

Visual Studio: Publish dialog - select container registry

Next, for the Container Registry, select the Subscription name that you used to create the ACR resource. From the Container registries selection area, select the container registry that you created, and then select Finish.

Visual Studio: Publish dialog - select container registry details

This creates a publish profile, which can be used to publish the image to container registry. Select the Publish button to push the image to the container registry, the Output window reports the publish progress—and when it completes successfully, you'll see a "Successfully published" message.

Select Docker from the Activity Bar in Visual Studio Code. Expand the IMAGES tree view panel, then expand the appcloudservice image node and right-click on the latest tag.

Visual Studio Code: Docker - push image

The integrated terminal window will report the progress of the docker push command to the container registry.

To push an image to the container registry, you need to sign in to the registry first:

az acr login -n <registry name>

The az acr login command will sign in to a container registry through the Docker CLI. To push the image to the container registry, use the az acr build command with your container registry name as the <registry name>:

az acr build -r <registry name> -t appcloudservice .

The preceding command:

  • Packs the source into a tar file.
  • Uploads it to the container registry.
  • The container registry unpacks the tar file.
  • Runs the docker build command in the container registry resource against the Dockerfile.
  • Adds the image to the container registry.

To verify that the image was successfully pushed to the container registry, navigate to the Azure portal. Open the container registry resource, under Services, select Repositories. You should see the image.

Deploy as container instance

From Visual Studio Code, select Docker from the Activity Bar. Expand the REGISTRIES node, and select Connect Registry. Select Azure when prompted, and sign in if necessary.

Visual Studio Code - Docker: Connect registry

Expand the REGISTRIES node, select Azure, your subscription > the container registry > the image, and then right-click the tag. Select Deploy Image to Azure Container Instances.

Visual Studio Code - Docker: Deploy image to Azure Container Instances

To create a container instance, you'll need to create a container group using the az container create command.

az container create -g <resource group> \
  --name <instance name> \
  --image <registry name>.azurecr.io/<image name>:latest \
  --registry-password <password>

Provide the appropriate values:

  • <resource group>: the resource group name that you've been using in this tutorial.
  • <instance name>: the name of the container instance.
  • <registry name>: the name of the container registry.
  • <image name>: the name of the image.
  • <password>: the password to the container registry—you can get this from the Azure portal, Container Registry resource > Access Keys.

To create a container instance, you'll need to create a new resource in the Azure portal.

  1. Select the same Subscription, and corresponding Resource group from the previous section.
  2. Enter a Container nameappcloudservice-container.
  3. Select a Region that corresponds to the previous Location selection.
  4. For Image source, select Azure Container Registry.
  5. Select the Registry by the name provided in the previous step.
  6. Select the Image and Image tag.
  7. Select Review + create.
  8. Assuming Validation passed, select Create.

It may take a moment for the resources to be created, once created select the Go to resource button.

For more information, see Quickstart: Create an Azure container instance.

Verify service functionality

Immediately after the container instance is created, it starts running.

To verify your worker service is functioning correctly, navigate to the Azure portal in the container instance resource, select the Containers option.

Azure portal: Container instance running

You'll see the containers, and their current State. In this case, it will be Running. Select Logs to see the .NET worker service output.

To verify your worker service is functioning correctly, you can view the logs from your running application. Use the az container logs command:

az container logs -g <resource group> --name <instance name>

Provide the appropriate values:

  • <resource group>: the resource group name that you've been using in this tutorial.
  • <instance name>: the name of the container instance.

You'll see the .NET worker service output logs, which means you've successfully deployed your containerized app to ACI.

See also