- Notifications
You must be signed in to change notification settings - Fork383
🐳 .NET (C#) Client Library for Docker API
License
dotnet/Docker.DotNet
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This library allows you to interact withDocker Remote API endpoints in your .NET applications.
It is fully asynchronous, designed to be non-blocking and object-oriented way to interact with your Docker daemon programmatically.
Version of this package usesSemVer format:MAJOR.MINOR.PATCH
.MINOR
segment indicatestheDocker Remote API version support. For instancev2.124.0
of this library supportsDocker Remote APIv1.24
. This does not guarantee backwards compatibility asDocker Remote API does not guarantee that either.
MAJOR
is reserved for major breaking changes we make to the library itself such as howthe calls are made or how authentication is made.PATCH
is just for incremental bug fixesor non-breaking feature additions.
You can add this library to your project usingNuGet.
Package Manager ConsoleRun the following command in the “Package Manager Console”:
PM> Install-Package Docker.DotNet
Visual StudioRight click to your project in Visual Studio, choose “Manage NuGet Packages” and search for ‘Docker.DotNet’ and click ‘Install’.(see NuGet Gallery.)
.NET Core Command Line InterfaceRun the following command from your favorite shell or terminal:
dotnet add package Docker.DotNet
Development Builds
If you intend to use development builds of Docker.DotNet and don't want to compile the code yourself you can add the package source below to Visual Studio or your Nuget.Config.
You can initialize the client like the following:
usingDocker.DotNet;DockerClientclient=newDockerClientConfiguration(newUri("http://ubuntu-docker.cloudapp.net:4243")).CreateClient();
or to connect to your localDocker for Windows daemon using named pipes or your localDocker for Mac daemon using Unix sockets:
usingDocker.DotNet;DockerClientclient=newDockerClientConfiguration().CreateClient();
For a custom endpoint, you can also pass a named pipe or a Unix socket to theDockerClientConfiguration
constructor. For example:
// Default Docker Engine on WindowsusingDocker.DotNet;DockerClientclient=newDockerClientConfiguration(newUri("npipe://./pipe/docker_engine")).CreateClient();// Default Docker Engine on LinuxusingDocker.DotNet;DockerClientclient=newDockerClientConfiguration(newUri("unix:///var/run/docker.sock")).CreateClient();
IList<ContainerListResponse>containers=awaitclient.Containers.ListContainersAsync(newContainersListParameters(){Limit=10,});
The code below pullsfedora/memcached
image to your Docker instance using your Docker Hub account. You cananonymously download the image as well by passingnull
instead of AuthConfig object:
awaitclient.Images.CreateImageAsync(newImagesCreateParameters{FromImage="fedora/memcached",Tag="alpha",},newAuthConfig{Email="test@example.com",Username="test",Password="pa$$w0rd"},newProgress<JSONMessage>());
The following code will create a new container of the previously fetched image.
awaitclient.Containers.CreateContainerAsync(newCreateContainerParameters(){Image="fedora/memcached",HostConfig=newHostConfig(){DNS=new[]{"8.8.8.8","8.8.4.4"}}});
The following code will start the created container.
awaitclient.Containers.StartContainerAsync("39e3317fd258",newContainerStartParameters());
The following code will stop a running container.
Note:WaitBeforeKillSeconds
field is of typeuint?
which means optional. This code will wait 30 seconds beforekilling it. If you like to cancel the waiting, you can use the CancellationToken parameter.
varstopped=awaitclient.Containers.StopContainerAsync("39e3317fd258",newContainerStopParameters{WaitBeforeKillSeconds=30},CancellationToken.None);
Some Docker API endpoints are designed to return stream responses. For exampleMonitoring Docker eventscontinuously streams the status in a format like :
{"status":"create","id":"dfdf82bd3881","from":"base:latest","time":1374067924}{"status":"start","id":"dfdf82bd3881","from":"base:latest","time":1374067924}{"status":"stop","id":"dfdf82bd3881","from":"base:latest","time":1374067966}{"status":"destroy","id":"dfdf82bd3881","from":"base:latest","time":1374067970}...
To obtain this stream you can use:
CancellationTokenSourcecancellation=newCancellationTokenSource();Streamstream=awaitclient.System.MonitorEventsAsync(newContainerEventsParameters(),newProgress<JSONMessage>(),cancellation.Token);// Initialize a StreamReader...
You can cancel streaming using the CancellationToken. On the other hand, if you wish to continuously stream, you can simply passCancellationToken.None
.
If you arerunning Docker with TLS (HTTPS), you can authenticate to the Docker instance using theDocker.DotNet.X509
package. You can get this package from NuGet or by running the following command in the “Package Manager Console”:
PM> Install-Package Docker.DotNet.X509
Once you addDocker.DotNet.X509
to your project, useCertificateCredentials
type:
varcredentials=newCertificateCredentials(newX509Certificate2("CertFile","Password"));varconfig=newDockerClientConfiguration("http://ubuntu-docker.cloudapp.net:4243",credentials);DockerClientclient=config.CreateClient();
If you don't want to authenticate you can omit thecredentials
parameter, which defaults to anAnonymousCredentials
instance.
TheCertFile
in the example above should be a .pfx file (PKCS12 format), if you have .pem formatted certificates which Docker normally uses you can either convert it programmatically or useopenssl
tool to generate a .pfx:
openssl pkcs12 -export -inkey key.pem -in cert.pem -out key.pfx
(Here, your private key is key.pem, public key is cert.pem and output file is named key.pfx.) This will prompt a password for PFX file and then you can use this PFX file on Windows. If the certificate is self-signed, your application may reject the server certificate, in this case you might want to disable server certificate validation:
//// There are two options to do this.//// You can do this globally for all certificates:ServicePointManager.ServerCertificateValidationCallback+=(o,c,ch,er)=>true;// Or you can do this on a credential by credential basis:varcreds=newCertificateCredentials(...);creds.ServerCertificateValidationCallback+=(o,c,ch,er)=>true;
If the Docker instance is secured with Basic HTTP Authentication, you can use theDocker.DotNet.BasicAuth
package. Get this package from NuGet or by running the following command in the “Package Manager Console”:
PM> Install-Package Docker.DotNet.BasicAuth
Once you addedDocker.DotNet.BasicAuth
to your project, useBasicAuthCredentials
type:
varcredentials=newBasicAuthCredentials("YOUR_USERNAME","YOUR_PASSWORD");varconfig=newDockerClientConfiguration("tcp://ubuntu-docker.cloudapp.net:4243",credentials);DockerClientclient=config.CreateClient();
BasicAuthCredentials
also acceptsSecureString
for username and password arguments.
By default this client does not specify version number to the API for the requests it makes. However, if you would like to make use of versioning feature of Docker Remote API You can initialize the client like the following.
varconfig=newDockerClientConfiguration(...);DockerClientclient=config.CreateClient(newVersion(1,16));
Here are typical exceptions thrown from the client library:
DockerApiException
is thrown when Docker API responds with a non-success result. Subclasses:DockerContainerNotFoundException
DockerImageNotFoundException
TaskCanceledException
is thrown fromSystem.Net.Http.HttpClient
library by design. It is not a friendly exception, but it indicates your request has timed out. (default request timeout is 100 seconds.)- Long-running methods (e.g.
WaitContainerAsync
,StopContainerAsync
) and methods that return Stream (e.g.CreateImageAsync
,GetContainerLogsAsync
) have timeout value overridden with infinite timespan by this library.
- Long-running methods (e.g.
ArgumentNullException
is thrown when one of the required parameters are missing/empty.- Consider reading theDocker Remote API reference and source code of the corresponding method you are going to use in from this library. This way you can easily find out which parameters are required and their format.
Docker.DotNet is a.NET Foundation project.
There are many .NET related projects on GitHub.
- .NET home repo - links to 100s of .NET projects, from Microsoft and the community.
- ASP.NET Core home - the best place to start learning about ASP.NET Core.
This project has adopted the code of conduct defined by theContributor Covenant to clarify expected behavior in our community. For more information, see the.NET Foundation Code of Conduct.
General .NET OSS discussions:.NET Foundation Discord
This project welcomes contributions and suggestions. Most contributions require you to agree to aContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant usthe rights to use your contribution. For details, visithttps://cla.dotnetfoundation.org.
When you submit a pull request, a CLA-bot will automatically determine whether you need to providea CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructionsprovided by the bot. You will only need to do this once across all repos using our CLA.
Docker.DotNet is licensed under theMIT license.
Copyright (c) .NET Foundation and Contributors
About
🐳 .NET (C#) Client Library for Docker API