免责声明 - 这与docker container exits immediately even with Console.ReadLine() in a .net core console application几乎是同一个问题 - 但我不认为这个问题的公认答案是令人满意的。
我想要实现的目标
我正在构建一个控制台应用程序(它是一个使用ServiceStack的HTTP服务),它是用.NET核心构建的(dnxcore50 - 这是一个控制台应用程序,而不是ASP.NET应用程序)。我在Linux机器上的docker容器中运行此应用程序。我已经完成了,HTTP服务正常工作。
我的问题
说过“我的服务有效” - 确实如此,在docker容器中托管服务存在问题。我在启动HTTP侦听器后使用Console.ReadLine()
,但此代码不会在docker容器中阻塞,并且容器将在启动后立即退出。我可以在“交互”模式下启动docker容器,服务将在那里监听,直到我终止交互式会话,然后容器将退出。
回购代码
下面的代码是一个完整的代码清单,用于创建我的测试.NET核心Servicestack控制台应用程序。
public class Program
{
public static void Main(string[] args)
{
new AppHost().Init().Start("http://*:8088/");
Console.WriteLine("listening on port 8088");
Console.ReadLine();
}
}
public class AppHost : AppSelfHostBase
{
// Initializes your AppHost Instance, with the Service Name and assembly containing the Services
public AppHost() : base("My Test Service", typeof(MyTestService).GetAssembly()) { }
// Configure your AppHost with the necessary configuration and dependencies your App needs
public override void Configure(Container container)
{
}
}
public class MyTestService: Service
{
public TestResponse Any(TestRequest request)
{
string message = string.Format("Hello {0}", request.Name);
Console.WriteLine(message);
return new TestResponse {Message = message};
}
}
[Api("Test method")]
[Route("/test/{Name}", "GET", Summary = "Get Message", Notes = "Gets a message incorporating the passed in name")]
public class TestRequest : IReturn<TestResponse>
{
[ApiMember(Name = "Name", Description = "Your Name", ParameterType = "path", DataType = "string")]
public string Name { get; set; }
}
public class TestResponse
{
[ApiMember(Name = "Message", Description = "A Message", ParameterType = "path", DataType = "string")]
public string Message { get; set; }
}
解决此问题的旧方法
所以以前使用Mono托管(Mono有严重的性能问题 - 因此切换到.NET内核) - 修复此行为的方法是使用Mono.Posix
监听这样的kill信号:
using Mono.Unix;
using Mono.Unix.Native;
...
static void Main(string[] args)
{
//Start your service here...
// check if we're running on mono
if (Type.GetType("Mono.Runtime") != null)
{
// on mono, processes will usually run as daemons - this allows you to listen
// for termination signals (ctrl+c, shutdown, etc) and finalize correctly
UnixSignal.WaitAny(new[] {
new UnixSignal(Signum.SIGINT),
new UnixSignal(Signum.SIGTERM),
new UnixSignal(Signum.SIGQUIT),
new UnixSignal(Signum.SIGHUP)
});
}
else
{
Console.ReadLine();
}
}
现在 - 我明白这对.NET Core不起作用(显然是因为Mono.Posix适用于Mono!)
相关文章(本文顶部)中概述的解决方案对我没有用处 - 在生产环境中,我不能指望通过确保它具有可用的交互式会话来保持docker容器的活着。 Console.ReadLine正常工作,因为那里有STD-IN流...
在托管.NET Core应用程序时,还有另一种方法可以让我的docker容器保持活动状态(在调用-d
时使用docker run
(分离)选项吗?
代码重构是Mythz建议的一部分
public static void Main(string[] args)
{
Run(new AppHost().Init(), "http://*:8088/");
}
public static void Run(ServiceStackHost host, params string[] uris)
{
AppSelfHostBase appSelfHostBase = (AppSelfHostBase)host;
using (IWebHost webHost = appSelfHostBase.ConfigureHost(new WebHostBuilder(), uris).Build())
{
ManualResetEventSlim done = new ManualResetEventSlim(false);
using (CancellationTokenSource cts = new CancellationTokenSource())
{
Action shutdown = () =>
{
if (!cts.IsCancellationRequested)
{
Console.WriteLine("Application is shutting down...");
cts.Cancel();
}
done.Wait();
};
Console.CancelKeyPress += (sender, eventArgs) =>
{
shutdown();
// Don't terminate the process immediately, wait for the Main thread to exit gracefully.
eventArgs.Cancel = true;
};
Console.WriteLine("Application started. Press Ctrl+C to shut down.");
webHost.Run(cts.Token);
done.Set();
}
}
}
最终解决方案!
对于后代 - 我所使用的解决方案是可在此处找到的代码(感谢神话澄清):https://github.com/NetCoreApps/Hello/blob/master/src/SelfHost/Program.cs
相关代码的回购:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls("http://*:8088/")
.Build();
host.Run();
}
}
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// app.UseStaticFiles();
app.UseServiceStack(new AppHost());
app.Run(context =>
{
context.Response.Redirect("/metadata");
return Task.FromResult(0);
});
}
在NuGet中,我安装了Microsoft.NETCore.App,ServiceStack.Core和ServiceStack.Kestrel。
答案 0 :(得分:10)
如果您要在Docker中托管.NET Core应用程序,我建议您按照正常的.NET Core Hosting API调用IWebHost.Run()
来阻止主线程并保留控制台应用程序活着。
AppHostSelfBase仅为wrapper around .NET Core's hosting API,但会调用非阻塞IWebHost.Start()
。要获得IWebHost.Run()
的行为,您应该能够重用ManualResetEventSlim
和Console.CancelKeyPress
WebHost.Run()'s implementation uses的相同方法,但就个人而言,它更容易使用。 NET Core的托管API并致电Run()
并致电register your ServiceStack AppHost as a .NET Core module。