docker container exits immediately even with Console.ReadLine() in a .NET Core console application

后端 未结 9 1627
一个人的身影
一个人的身影 2020-12-09 15:43

I am trying to run a .NET Core 1.0.0 console application inside a docker container.
When I run dotnet run command from inside the Demo folder on my machin

9条回答
  •  伪装坚强ぢ
    2020-12-09 16:02

    For those that what to run your .net 4.x console app in linux docker without having to specified -i and want to run it in the background, the best solution is mono.posix package, which does exactly what we are looking for, listen to linux signals.

    this also applys to WebApi2 with Owin projects, or basically any console app

    for most of us running containers in the background using console.read or ManualResetEventSlim or AutoResetEvent wont worked because of detached mode by docker.

    The best solution is installing Install-Package Mono.Posix

    here's an example:

    using System;
    using Microsoft.Owin.Hosting;
    using Mono.Unix;
    using Mono.Unix.Native;
    
    public class Program
    {
        public static void Main(string[] args)
        {
            string baseAddress = "http://localhost:9000/"; 
    
            // Start OWIN host 
            using (WebApp.Start(url: baseAddress)) 
            { 
                Console.ReadLine(); 
            }
    
            if (IsRunningOnMono())
            {
                var terminationSignals = GetUnixTerminationSignals();
                UnixSignal.WaitAny(terminationSignals);
            }
            else
            {
                Console.ReadLine();
            }
    
            host.Stop();
        }
    
        public static bool IsRunningOnMono()
        {
            return Type.GetType("Mono.Runtime") != null;
        }
    
        public static UnixSignal[] GetUnixTerminationSignals()
        {
            return new[]
            {
                new UnixSignal(Signum.SIGINT),
                new UnixSignal(Signum.SIGTERM),
                new UnixSignal(Signum.SIGQUIT),
                new UnixSignal(Signum.SIGHUP)
            };
        }
    }
    

    full source blog post: https://dusted.codes/running-nancyfx-in-a-docker-container-a-beginners-guide-to-build-and-run-dotnet-applications-in-docker

提交回复
热议问题