Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 machine, it works fine; but when run using docker run -d --name demo Demo, the container exits immediately.

I tried docker logs demo to check the logs and it just shows the text from the Console.WriteLine:

Demo app running...

and nothing else.

I have uploaded the project at https://github.com/learningdockerandnetcore/Demo

The project contains Programs.cs, Dockerfile used to create Demo image, and project.json file.

like image 606
Learning Docker Avatar asked Jul 24 '16 05:07

Learning Docker


People also ask

Why does my docker container exit immediately?

You're running a shell in a container, but you haven't assigned a terminal: If you're running a container with a shell (like bash ) as the default command, then the container will exit immediately if you haven't attached an interactive terminal.

Is data lost when the docker container exits?

Do I lose my data when the container exits? 🔗 Not at all! Any data that your application writes to disk gets preserved in its container until you explicitly delete the container.

What happens when a docker container exits?

By default, what happens to a Docker Container when the process it is running exits? The Container reboots and restarts the process.


1 Answers

If you switch your app to target .NET Core 2.0, you can use the Microsoft.Extensions.Hosting package to host a .NET Core console application by using the HostBuilder API to start/stop your application. Its ConsoleLifetime class would process the general application start/stop method.

In order to run your app, you should implement your own IHostedService interface or inherit from the BackgroundService class, then add it to host context within ConfigureServices.

namespace Microsoft.Extensions.Hosting {     //     // Summary:     //     Defines methods for objects that are managed by the host.     public interface IHostedService     {         // Summary:         // Triggered when the application host is ready to start the service.         Task StartAsync(CancellationToken cancellationToken);          // Summary:         // Triggered when the application host is performing a graceful shutdown.         Task StopAsync(CancellationToken cancellationToken);     } } 

Here's a sample hosted service:

public class TimedHostedService : IHostedService, IDisposable {     private readonly ILogger _logger;     private Timer _timer;      public TimedHostedService(ILogger<TimedHostedService> logger)     {         _logger = logger;     }      public Task StartAsync(CancellationToken cancellationToken)     {         _logger.LogInformation("Timed Background Service is starting.");          _timer = new Timer(DoWork, null, TimeSpan.Zero,              TimeSpan.FromSeconds(5));          return Task.CompletedTask;     }      private void DoWork(object state)     {         _logger.LogInformation("Timed Background Service is working.");     }      public Task StopAsync(CancellationToken cancellationToken)     {         _logger.LogInformation("Timed Background Service is stopping.");          _timer?.Change(Timeout.Infinite, 0);          return Task.CompletedTask;     }      public void Dispose()     {         _timer?.Dispose();     } } 

Then creating the HostBuilder and adding the service and other components (logging, configuration).

public class Program {     public static async Task Main(string[] args)     {         var hostBuilder = new HostBuilder()              // Add configuration, logging, ...             .ConfigureServices((hostContext, services) =>             {                 // Add your services with depedency injection.             });          await hostBuilder.RunConsoleAsync();     } } 
like image 72
Feiyu Zhou Avatar answered Sep 19 '22 15:09

Feiyu Zhou