Packaging .NET console apps in Docker

Console apps are easy to build as good citizens for Docker. The compiled executable for the app will be the main process that Docker starts and monitors, so you just need to make use of the console for logging and you can use files and environment variables for configuration.

For my message handler, I'm using a Dockerfile with a slightly different pattern. I have a separate image for the builder stage that I use to compile the whole solution—both the web project and the new projects I've added. I'll walk through the builder image later in the chapter once you've seen all the new components.

The builder compiles the solution and the Dockerfile for the console application references the dockeronwindows/ch05-nerd-dinner-builder:2e image to copy out the compiled binaries. The whole Dockerfile is very simple:

# escape=`
FROM mcr.microsoft.com/windows/servercore:ltsc2019

CMD ["NerdDinner.MessageHandlers.SaveDinner.exe"]

WORKDIR
C:save-handler
COPY
--from=dockeronwindows/ch05-nerd-dinner-builder:2e `
C:srcNerdDinner.MessageHandlers.SaveDinnerobjRelease .
The from argument in the COPY instruction specifies the source of the files. It can be another stage in a multistage build, or—as in this example—an existing image on the local machine or a registry.

The new message handler needs to access the message queue and the database, and the connection strings for each are captured in the project's appsettings.json file. The console app uses the same Config class as the NerdDinner web app, which loads default values from the JSON file and can override them from environment variables.

In the Dockerfile, the entry point in the CMD instruction is the console executable, so the container will keep running as long as the console app is running. The listener for the message queue runs asynchronously on a separate thread to the main application. The handler code will fire when a message is received, so there's no polling of the queue, and the app runs very efficiently.

Keeping the console app running indefinitely is straightforward using a ManualResetEvent object. In the Main method, I wait for a reset event that never happens, so the program keeps running:

class Program
{
private static ManualResetEvent _ResetEvent = new ManualResetEvent(false);

static void Main(string[] args)
{
// set up message listener
_ResetEvent.WaitOne();
}
}

This is a simple and efficient way of keeping a .NET Framework or a .NET Core console app alive. When I start a message handler container, it will keep running in the background and listen for messages until the container is stopped.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.157