Created
September 28, 2020 17:43
-
-
Save raholsn/8ab21851341d91f9bd0c7af947765404 to your computer and use it in GitHub Desktop.
Docker.Dotnet, accessing Docker Host Remote API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Runtime.InteropServices; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Docker.DotNet; | |
using Docker.DotNet.Models; | |
namespace Docker.Library | |
{ | |
public class DockerHost : IAsyncDisposable | |
{ | |
private static readonly bool IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); | |
private static readonly bool IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); | |
private readonly DockerClient _dockerClient; | |
public DockerHost() | |
{ | |
_dockerClient = new DockerClientConfiguration( new Uri(DockerApiUri())).CreateClient(); | |
} | |
private async Task PullImageIfNotExist(string image, CancellationToken ct = default) | |
{ | |
var existingContainers = await _dockerClient.Containers.ListContainersAsync(new ContainersListParameters | |
{ | |
All = true | |
}, ct); | |
var exists = existingContainers.Any(x => x.Image == image); | |
if (!exists) | |
{ | |
await _dockerClient.Images.CreateImageAsync(new ImagesCreateParameters | |
{ | |
FromImage = image, | |
}, null, null, ct); | |
} | |
} | |
private async Task<string> CreateContainer(string image,string containerName, CancellationToken ct = default) | |
{ | |
await PullImageIfNotExist(image, ct); | |
return (await _dockerClient.Containers.CreateContainerAsync(new CreateContainerParameters | |
{ | |
Image = image, | |
Name = containerName, | |
HostConfig = new HostConfig | |
{ | |
PublishAllPorts = true, | |
AutoRemove = true | |
} | |
}, ct)).ID; | |
} | |
public async Task StartContainer(string image,string containerName, CancellationToken ct = default) | |
{ | |
var containerId = await CreateContainer(image,containerName,ct); | |
await _dockerClient.Containers.StartContainerAsync(containerId, new ContainerStartParameters(), ct); | |
} | |
public ValueTask DisposeAsync() | |
{ | |
_dockerClient.Dispose(); | |
return new ValueTask(); | |
} | |
private static string DockerApiUri() | |
{ | |
if (IsWindows) | |
return "npipe://./pipe/docker_engine"; | |
if (IsLinux) | |
return "unix:///var/run/docker.sock"; | |
throw new Exception( | |
"Was unable to determine what OS this is running on, does not appear to be Windows or Linux!?"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment