Posted by Anuraj on Tuesday, July 10, 2018 Reading time :2 minutes
Hangfire is framework which helps to perform background operations in .NET and .NET Core. By default, Hangfire will be configured along with the application, but you need to configure the Web App to run Always running. For better scalability and separation of concerns, it is recommended to move the job processing from web application to a different process. Hangfire supports two modes, one as a Console application and as Windows Service. In this blog post I am using Console app approach.
First I am building the console application. It is simple and straight forward - I am just following the steps mentioned in the Hangfire website.
BackgroundJobServer. Here is the code.
If you notice, it is different from what is mentioned in the Hangfire website, because
Console.ReadKey() will not work in Docker. So instead of that I am using a
AutoResetEvent class, which will set only when the OS is shutting down.
Next you need to prepare the app to run in Docker. First you need to create a docker file. I am not using Visual Studio Add Docker support option. Here is the minimal Docker file.
Since we are using full framework I am using
windowsservercore image, this might take sometime to download. Next I am copying the Release folder to the container and finally setting the entry point as our console application.
You can build the image using this command -
docker build --tag dotnetthoughts/hangfire:v1 .
Here is the screenshot of docker build on my system.
Next you need to run the application, before running the command, you may need to modify the SQL Server connection string. Sometimes connecting to SQL Server running on Host from container may not work with usual hostname or IP Address. You need to get the Host IP Address, which Docker container can connect. You can run the
ipconfig command, and look for DockerNAT.
And use the IP Address in the server in the connection string instead of the hostname or IP Address.
Compile the code and build the image again. Once the image is ready, you can run it using
docker run -d --name hangfireconsole dotnetthoughts/hangfire:v1. Once it started, you can check this log using
docker logs <image name>;
It will show something like this.
Now you’re successfully deployed the .NET Framework Console application to Docker.
Happy Programming :)
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.