Dockerizing a .NET Core application with dotnet watch

Dockerizing a .NET Core application with dotnet watch
Photo by NEOM / Unsplash

This post will present a couple of snippets which are useful when dockerizing applications, and will contain certain commands and instructions used in both the Dockerfile and Docker-compose.yml file.

In order to setup a docker container for a .NET Core with dotnet watch application the following environment variables and commands are required within the container:

  • ASPNETCORE_URLS: "http://+:80" : Tells the web app to run on port 80.

    This since Docker containers aren't fond of URLs containing localhost such as the ones in Properties/launchSettings.json inside of a .NET Core project.

  • DOTNET_USE_POLLING_FILE_WATCHER : 1 : Enables the polling of the filesystem (more information here).

    This variable is required for the command dotnet watch to work. The watcher polls the filesystems every four seconds for changes, which enables the modification of the source files locally and have .Net Core automatically reload them.

  • dotnet restore && dotnet watch run --no-launch-profile :
    This command tells the container to run dotnet restore, which uses NuGet to restore dependencies as well as project-specific tools that are specified in the project file.

    Then dotnet watch run , which runs the source code using the filesystem watcher.
    The last part of the command we tell dotnet watch run to not use the launchSettings.json file by passing --no-launch-profile, which otherwise would determine the URLs which will be used among other settings.

Applying all the mentioned variables and commands in a docker-compose.yml file, would give us the following example below:

version: "3.7"
services:
  app:
    image: mcr.microsoft.com/dotnet/core/sdk:3.1
    container_name: my-app
    environment: 
        - ASPNETCORE_URLS=http://+:80
        - DOTNET_USE_POLLING_FILE_WATCHER=1
    volumes:
        - ./app:/app
    ports:
        - 8080:80
    working_dir: /app
    command: bash -c "dotnet restore && dotnet watch run --no-launch-profile"

Note: working_dir: sets the container’s working directory, which the command command: bash -c "dotnet restore && dotnet watch run --no-launch-profile" is executed once the container starts up.

Bonus Environment variable

To turn off .NET SDK telemetry, which collects usages data and exception information when .NET CLI cashes and sends it to Microsoft . Set this environment variable in the docker-compose file :
DOTNET_CLI_TELEMETRY_OPTOUT: 1

Written: 2021-03-18