How to set restart policy via Dockerfile or Docker.DotNet.IContainerOperations.StartContainerAsync

152 Views Asked by At

I need to set restart policy --restart unless-stopped for my Docker container.

I'm using Dockerfile to configure container with next example content:

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build-env
FROM mcr.microsoft.com/dotnet/aspnet:6.0
WORKDIR /app
COPY . ./
ENTRYPOINT ["asd", "proj.dll"]

And using Docker.DotNet to launch containers with next example code:

            container.StartContainerAsync(container.ID, null);

How to set that policy in that case? Perhaps I can use ContainerStartParameters somehow?

1

There are 1 best solutions below

0
Ivan Andreev On

Via Dockerfile: You can't. It's just impossible.

Via Docker.Dotnet You can set restart policy with following code:

using Docker.DotNet;
using Docker.DotNet.Models;
using System;

class Program
{
    static async Task Main(string[] args)
    {
        var dockerClient = new DockerClientConfiguration(new Uri("http://localhost:2375")).CreateClient();
        var createParameters = new CreateContainerParameters
        {
            Image = "ubuntu:latest",
            Cmd = new List<string> { "bash", "-c", "echo 'Hello World'" },
            HostConfig = new HostConfig
            {
                RestartPolicy = new RestartPolicy
                {
                    Name = "unless-stopped"
                }
            }
        };
        var response = await dockerClient.Containers.CreateContainerAsync(createParameters);
        await dockerClient.Containers.StartContainerAsync(response.ID, null);
    }
}