Code Monkey home page Code Monkey logo

docker.dotnet's Introduction

.NET Client for Docker Remote API

This library allows you to interact with Docker 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.

Versioning

Version of this package uses SemVer format: MAJOR.MINOR.PATCH. MINOR segment indicates the Docker Remote API version support. For instance v2.124.0 of this library supports Docker Remote API v1.24. This does not guarantee backwards compatibility as Docker Remote API does not guarantee that either.

MAJOR is reserved for major breaking changes we make to the library itself such as how the calls are made or how authentication is made. PATCH is just for incremental bug fixes or non-breaking feature additions.

Installation

NuGet latest release

You can add this library to your project using NuGet.

Package Manager Console Run the following command in the “Package Manager Console”:

PM> Install-Package Docker.DotNet

Visual Studio Right 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 Interface Run 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.

https://ci.appveyor.com/nuget/docker-dotnet-hojfmn6hoed7

Usage

You can initialize the client like the following:

using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("http://ubuntu-docker.cloudapp.net:4243"))
     .CreateClient();

or to connect to your local Docker for Windows daemon using named pipes or your local Docker for Mac daemon using Unix sockets:

using Docker.DotNet;
DockerClient client = new DockerClientConfiguration()
     .CreateClient();

For a custom endpoint, you can also pass a named pipe or a Unix socket to the DockerClientConfiguration constructor. For example:

// Default Docker Engine on Windows
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("npipe://./pipe/docker_engine"))
     .CreateClient();
// Default Docker Engine on Linux
using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(
    new Uri("unix:///var/run/docker.sock"))
     .CreateClient();

Example: List containers

IList<ContainerListResponse> containers = await client.Containers.ListContainersAsync(
	new ContainersListParameters(){
		Limit = 10,
    });

Example: Create an image by pulling from Docker Registry

The code below pulls fedora/memcached image to your Docker instance using your Docker Hub account. You can anonymously download the image as well by passing null instead of AuthConfig object:

await client.Images.CreateImageAsync(
    new ImagesCreateParameters
    {
        FromImage = "fedora/memcached",
        Tag = "alpha",
    },
    new AuthConfig
    {
        Email = "[email protected]",
        Username = "test",
        Password = "pa$$w0rd"
    },
    new Progress<JSONMessage>());

Example: Create a container

The following code will create a new container of the previously fetched image.

await client.Containers.CreateContainerAsync(new CreateContainerParameters()
    {
        Image = "fedora/memcached",
        HostConfig = new HostConfig()
        {
            DNS = new[] { "8.8.8.8", "8.8.4.4" }
        }
    });

Example: Start a container

The following code will start the created container.

await client.Containers.StartContainerAsync(
    "39e3317fd258",
    new ContainerStartParameters()
    );

Example: Stop a container

The following code will stop a running container.

Note: WaitBeforeKillSeconds field is of type uint? which means optional. This code will wait 30 seconds before killing it. If you like to cancel the waiting, you can use the CancellationToken parameter.

var stopped = await client.Containers.StopContainerAsync(
    "39e3317fd258",
    new ContainerStopParameters
    {
        WaitBeforeKillSeconds = 30
    },
    CancellationToken.None);

Example: Dealing with Stream responses

Some Docker API endpoints are designed to return stream responses. For example Monitoring Docker events continuously 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:

CancellationTokenSource cancellation = new CancellationTokenSource();
Stream stream = await client.System.MonitorEventsAsync(new ContainerEventsParameters(), new Progress<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 pass CancellationToken.None.

Example: HTTPS Authentication to Docker

If you are running Docker with TLS (HTTPS), you can authenticate to the Docker instance using the Docker.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 add Docker.DotNet.X509 to your project, use CertificateCredentials type:

var credentials = new CertificateCredentials (new X509Certificate2 ("CertFile", "Password"));
var config = new DockerClientConfiguration("http://ubuntu-docker.cloudapp.net:4243", credentials);
DockerClient client = config.CreateClient();

If you don't want to authenticate you can omit the credentials parameter, which defaults to an AnonymousCredentials instance.

The CertFile 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 use openssl 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:
var creds = new CertificateCredentials(...);
creds.ServerCertificateValidationCallback += (o, c, ch, er) => true;

Example: Basic HTTP Authentication to Docker

If the Docker instance is secured with Basic HTTP Authentication, you can use the Docker.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 added Docker.DotNet.BasicAuth to your project, use BasicAuthCredentials type:

var credentials = new BasicAuthCredentials ("YOUR_USERNAME", "YOUR_PASSWORD");
var config = new DockerClientConfiguration("tcp://ubuntu-docker.cloudapp.net:4243", credentials);
DockerClient client = config.CreateClient();

BasicAuthCredentials also accepts SecureString for username and password arguments.

Example: Specifying Remote API Version

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.

var config = new DockerClientConfiguration(...);
DockerClient client = config.CreateClient(new Version(1, 16));

Error Handling

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 from System.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.
  • ArgumentNullException is thrown when one of the required parameters are missing/empty.
    • Consider reading the Docker 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.

.NET Foundation

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 the Contributor 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

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.dotnetfoundation.org.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

License

Docker.DotNet is licensed under the MIT license.


Copyright (c) .NET Foundation and Contributors

docker.dotnet's People

Contributors

0x7c13 avatar 0xced avatar ahmetb avatar anonpenguin avatar cfauchere avatar davipb avatar dudes-come avatar emdot avatar galvesribeiro avatar hofmeisteran avatar itsverywindy avatar jgarverick avatar jonso4 avatar jstarks avatar jterry75 avatar lippertmarkus avatar markdchurchill avatar mgissing avatar mortonfox avatar msdeibel avatar msftgits avatar nickwesselman avatar novinc avatar rjperes avatar sandersaares avatar stefanprodan avatar sumo-mbryant avatar swernli avatar toolboc avatar tugberkugurlu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

docker.dotnet's Issues

publish 2.X

when will you publish a new version of the Docker.DotNet to nuget?

there are a lot of cool new features you have added and i would like to implement them in my codebase.

cheers,
ASTRO

QueryStringConverterInstanceFactory is not thread safe

This QueryStringConverterInstanceFactory file is not thread safe. https://github.com/Microsoft/Docker.DotNet/blob/master/Docker.DotNet/QueryStringConverterInstanceFactory.cs

What version of Docker.DotNet?:
Latest NuGet version

Stacktrace:
Object reference not set to an instance of an object.
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary2.set_Item(TKey key, TValue value)
at Docker.DotNet.QueryStringConverterInstanceFactory.GetConverterInstance(Type t)
at Docker.DotNet.QueryString1.GetKeyValuePairs() at Docker.DotNet.QueryString1.GetQueryString()
at Docker.DotNet.HttpUtility.BuildUri(Uri baseUri, Version requestedApiVersion, String path, IQueryString queryString)
at Docker.DotNet.DockerClient.PrepareRequest(HttpMethod method, String path, IQueryString queryString, IDictionary2 headers, IRequestContent data) at Docker.DotNet.DockerClient.MakeRequestInnerAsync(Nullable1 requestTimeout, HttpCompletionOption completionOption, HttpMethod method, String path, IQueryString queryString, IDictionary`2 headers, IRequestContent data, CancellationToken cancellationToken)
at Docker.DotNet.DockerClient.d__40.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Docker.DotNet.ContainerOperations.d__6.MoveNext()

Unix socket compatibility problem

//case "unix":
// TODO

May i ask when dockerClient is going to support unix://var/run/docker.sock as this is supported in other docker remote api client such as python one.

Issues in compilation when used with python related dependencies

Using v2.124.1, I was trying to add references to IronPython, Microsoft.Scripting, and Microsoft.Dynamic. Upon building and compiling the application, I get the following error:

Server Error in '/' Application.

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0121: The call is ambiguous between the following methods or properties: 'System.TypeExtensions.GetTypeInfo(System.Type)' and 'System.Reflection.IntrospectionExtensions.GetTypeInfo(System.Type)'

Source Error:
Line 11: public bool CanConvert(Type t)
Line 12: {
Line 13: return typeof (IList).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo()) || typeof (IDictionary).GetTypeInfo().IsAssignableFrom(t.GetTypeInfo());
Line 14: }
Line 15:

If i remove the references to the above dll's the compilation works fine. Any advice as to how to get around this issue?

Using StartContainerExecAsync for capturing stream output

I am using the 2.124 version of the API. The objective of the problem is to exec into a running container by passing in a command to print text to console and extract the same back using the stream output. Below is the code snippet. The startcontainerexec returns a reponse 200 - status:OK, but the stream parameters Length, Seek, etc. are not populated. I was able to extract the logs in case I started a container with an entrypoint command to keep the container running - for example, running a httpd server on the container and using docker logs. Although this is great, it doesnt solve the purpose of exec at any time into a running container and extracting the output on console. Any suggestions as to how an exec can be done using the API to get a streamed output back either through docker logs or a different spec of the exec from the one below?
Code:
private IList = new IList();
public async Task<IList> list_containers()
{
var dockerConfiguration = new DockerClientConfiguration(this.uri);
DockerClient client = dockerConfiguration.CreateClient();
this.containers_list = await client.Containers.ListContainersAsync(new ContainersListParameters()
{
All = true
});
IEnumerable names = (from l in this.containers_list select l.Names.First());
string id = this.containers_list[0].ID;
ContainerExecCreateResponse c = await client.Containers.ExecCreateContainerAsync(id, new ContainerExecCreateParameters()
{
Detach = false,
Tty = false,
Cmd = new List() { "ls" }
});
await client.Containers.StartContainerExecAsync(c.ID, CancellationToken.None);
do
{
var l = await client.Containers.GetContainerLogsAsync(id, new ContainerLogsParameters()
{
ShowStderr = true,
ShowStdout = true,
}, CancellationToken.None);
Regex r = new Regex(@"hello");
Match m = r.Match(l.ToString());
if (m.Success)
{
string h = m.Groups[1].Value;
break;
}
} while (true);
return this.containers_list;
}

Nuget package for v2.124

@ahmetalpbalkan: Nuget package currently is at v1.2. Most of the new and useful calls around exec, resize and attach are referenced in the latest package. Any updates on when the nuget package would be updated? Question arises because cloning the repo does not address all the missing libraries needed for a successful execution of the project. Although I updated references based on the project.json file, I still am receiving build errors around 'The type 'Object' is defined in an assemby that is not referenced. You must add a reference to System.Runtime Version 4.0.0.0..', 'httpresponseheaders does not contain a definition for TryWithoutValidation'. Suggestions?

X509 NuGet Package Out of Date

The latest Docker.DotNet.X509 NuGet package appears to be out of sync with the latest Docker.DotNet package. When I attempt to create a CertificateCredentials object, the following exception is thrown:

Error starting session: Method 'get_Handler' in type 'Docker.DotNet.X509.CertificateCredentials' from assembly 'Docker.DotNet.X509, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

Mono Support

Is this lib Mono compatible?

Seems to create a client fine on Windows but I get this on OSX

var client = new DockerClientConfiguration(new Uri("tcp://10.0.1.43:2376")).CreateClient();

Could not load type 'Docker.DotNet.AnonymousCredentials' from assembly 'Docker.DotNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Using ExecCreateContainerResponse and ExecCreateContainerAsync

Hi, DockerDotNet API has really been useful to me for creating applications based on infrastructural changes and processes - thank you for such a string utility kit. Particularly, in reference to ExecCreateContainerAsync, the method returns the ExecCreateContainerResponse object. However, I do not see the responsive action being executed. Here are the Config parameters that I entered:

Config = new ExecCreateContainerConfig() {
AttachStdin = true,
AttachStdout = true,
AttachStderr = true,
Tty = true,
Cmd = new List<string>() {"mkdir" , "abc"  }
}

And here is the function call,

ExecCreateContainerResponse ex = await client.Containers.ExecCreateContainerAsync(cr.Id, new ExecCreateContainerParameters() { Config = ...<as given above>});

where, cr.Id is the ID of the container that I have been able to create and run using CreateContainerAsync and StartContainerAsync.
I expected that the outcome of the above instruction would result in the creation of a new directory "abc" within the container instance. Although the program executed successfully providing a valid ExecCreateContainerResponse (Id, Warnings), when I looked up, by attaching the container on console, I couldnt find the directory. My questions:

  1. How can this action be achieved - I am trying to get to a result similar to "docker exec -d containerName mkdir abc" on console prompt?
  2. In a general scenario, if the CMD were to be an instruction that produces a stream of output on screen, how can this execution be achieved and the result be viewed on Visual Studio console?

NuGet Package 1.1.2 Does Not Add Assembly

The latest NuGet package, 1.1.2, does not include the Docker.DotNet assembly. Instead, it includes a single file named "." "inside the packages\Docker.DotNet.1.1.2\lib\portable-net45+sl5+wp8+win8" folder.

Cannot convert type System.Int64 using Docker.DotNet.Models.BoolQueryStringConverter.

Hi,

I am using package nuget version 1.1.1.
Code :

 //Connect
            DockerClientConfiguration clientConfig = new DockerClientConfiguration(new Uri("http://ubuntu-docker.cloudapp.net:4243"));
            DockerClient client = clientConfig.CreateClient(new Version(1, 14));

            //List containers
            IList<ContainerListResponse> containers = client.Containers.ListContainersAsync(
    new ListContainersParameters()
    {
        Limit = 10,
    }).Result;

I have the exception :
Cannot convert type System.Int64 using Docker.DotNet.Models.BoolQueryStringConverter.

Using ListContainersAsync with Filters

Hi everyone, I'm trying to figure out how to use the ListContainersAsync's Filters, but I always get the same result, as if no filter is being used at all.
I can list only the containers with state created making a request to /containers/json?all=1&filters={"status":["created"]}, so I don't think it's an issue with the Docker API.

I tried filtering by Label and Status, like the example below:

client.Containers.ListContainersAsync(new ContainersListParameters
{
   All = true,
   Filters = new Dictionary<string, Dictionary<string, bool>>
       {
           {
               "status", new Dictionary<string, bool>
                   {
                       { "created", true }
                   }
           }
       } as IDictionary<string, IDictionary<string, bool>>
})

PS: I don't really know what the boolean parameter in the second Dictionary does, so I've just used true.

My environment information:

Docker.DotNet version: 2.124.1

.NET:

.NET Command Line Tools (1.0.0-preview2-003121)

Product Information:
 Version:            1.0.0-preview2-003121
 Commit SHA-1 hash:  1e9d529bc5

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.10586
 OS Platform: Windows
 RID:         win10-x64

Docker:

Client:
 Version:      1.12.1
 API version:  1.24
 Go version:   go1.6.3
 Git commit:   23cf638
 Built:
 OS/Arch:      linux/amd64

Server:
 Version:      1.12.1
 API version:  1.24
 Go version:   go1.6.3
 Git commit:   23cf638
 Built:
 OS/Arch:      linux/amd64

Add IDockerClient Interface

I'd like to begin using Docker.DotNet in a project. Adding an abstraction for DockerClient would help with unit testing code that uses this library. Something like:

public interface IDockerClient
{
    IImageOperations Images { get; }

    IContainerOperations Containers { get; }

    IMiscellaneousOperations Miscellaneous { get; }
}

Also, the return type for DockerClientConfiguration.CreateClient() could be changed to IDockerClient.

I'm open to submitting a PR, but wanted to check first whether you think this is valuable.

Installation of Docker.DotNet fails with: "Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache"

Tried to install Docker.DotNet 2.124.1 on Windows 10 in Visual Studio 15 Update 3, but that failed with "Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache".

What version of Docker.DotNet?:

2.124.1

Steps to reproduce the issue:

  1. Install Docker.DotNet 2.124.1 via Nuget on Windows 10 in a project targeting .NET 4.6

What actually happened?:
Installation of Docker.DotNet fails with "Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache"

What did you expect to happen?:
Package should install smoothly

Additional information:
According to this post: dotnet/aspnetcore#1157 , it can be fixed by adding System.Net.Runtime as build-type dependency.

Project should compile for netcore50 using latest dotnet CLI

The project.json file isn't in the right format to allow publishing for netcore50 on our desired runtimes with the latest dotnet CLI. #55 temporarily removes support for netstandard1.3 as a work-around, but long term we'd like to have the correct project.json to support netcore properly.

Docker Remote API access is not enabled on Docker for Windows

.NET Command Line Tools (1.0.0-preview2-003121)

Product Information:
 Version:            1.0.0-preview2-003121
 Commit SHA-1 hash:  1e9d529bc5

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.10586
 OS Platform: Windows
 RID:         win10-x64

What version of Docker.DotNet?:

2.124.1

Steps to reproduce the issue:

  1. We create a docker client with our presumed client configuration.
  2. Any attempt to access to remote api (list containers, start/stop container) fails with "Connection failed" error.

What actually happened?:
We suspect that remote api of Docker is not accessible. We use Docker for Windows and couldn't find any tutorial about how to enable access to it. Your help will be appreciated.

System.IO.FileNotFoundExceptionCould not load file or assembly 'Microsoft.Threading.Tasks, Version=1.0.12.0,

Hi,

Just came across this project, looks great!

However I just ran the sample from README to list containers but when it calls this

 var containers = await client.Containers.ListContainersAsync(
                new ListContainersParameters()
                {
                    Limit = 10,
                });

I get an error like this:

System.IO.FileNotFoundExceptionCould not load file or assembly 'Microsoft.Threading.Tasks, Version=1.0.12.0, Culture=neutral, 
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

Any ideas?

How to call remote shell commands in container?

I am so lucky to see Docker.DotNet.
Maybe this question is just about docker remote api.I want to know how can I remote post commands to shell in docker container.for example post "Python -V" to remote docker container?

Error parsing RestartPolicy from inspect response

Using Docker.DotNet 1.1.2.1 connecting to Docker 1.6.2. Calling docker.Containers.InspectContainerAsync("something") throws:

Error converting value "" to type 'Docker.DotNet.Models.RestartPolicyKind'. 
Path 'HostConfig.RestartPolicy.Name', line 1, position 1488.

Raw JSON response from inspection:

[{
    "AppArmorProfile": "",
    "Args": [
        "elasticsearch",
        "--cluster.name=test-41e9c0ab-dbc5-41ca-8265-c4151746a4a9"
    ],
    "Config": {
        "AttachStderr": false,
        "AttachStdin": false,
        "AttachStdout": false,
        "Cmd": [
            "elasticsearch",
            "--cluster.name=test-41e9c0ab-dbc5-41ca-8265-c4151746a4a9"
        ],
        "CpuShares": 0,
        "Cpuset": "",
        "Domainname": "",
        "Entrypoint": [
            "/docker-entrypoint.sh"
        ],
        "Env": [
            "PATH=/usr/share/elasticsearch/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            "LANG=C.UTF-8",
            "JAVA_VERSION=8u45",
            "JAVA_DEBIAN_VERSION=8u45-b14-2~bpo8+2",
            "CA_CERTIFICATES_JAVA_VERSION=20140324",
            "ELASTICSEARCH_VERSION=1.7.1"
        ],
        "ExposedPorts": {
            "9200/tcp": {},
            "9300/tcp": {}
        },
        "Hostname": "dd145bb87386",
        "Image": "elasticsearch:1.7.1",
        "Labels": {},
        "MacAddress": "",
        "Memory": 0,
        "MemorySwap": 0,
        "NetworkDisabled": false,
        "OnBuild": null,
        "OpenStdin": false,
        "PortSpecs": null,
        "StdinOnce": false,
        "Tty": false,
        "User": "",
        "Volumes": {
            "/usr/share/elasticsearch/data": {}
        },
        "WorkingDir": ""
    },
    "Created": "2015-09-04T13:18:55.886520689Z",
    "Driver": "aufs",
    "ExecDriver": "native-0.2",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "CapAdd": null,
        "CapDrop": null,
        "CgroupParent": "",
        "ContainerIDFile": "",
        "CpuShares": 0,
        "CpusetCpus": "",
        "Devices": null,
        "Dns": null,
        "DnsSearch": null,
        "ExtraHosts": null,
        "IpcMode": "",
        "Links": null,
        "LogConfig": {
            "Config": null,
            "Type": "json-file"
        },
        "LxcConf": null,
        "Memory": 0,
        "MemorySwap": 0,
        "NetworkMode": "",
        "PidMode": "",
        "PortBindings": null,
        "Privileged": false,
        "PublishAllPorts": true,
        "ReadonlyRootfs": false,
        "RestartPolicy": {
            "MaximumRetryCount": 0,
            "Name": ""
        },
        "SecurityOpt": null,
        "Ulimits": null,
        "VolumesFrom": null
    },
    "HostnamePath": "/mnt/b53c2b12-0aed-4083-aefc-7c4cb0046360/docker/containers/dd145bb873863187e1d3e508e475d36a65dddc8fb1fb8f4c74818e066169ff5d/hostname",
    "HostsPath": "/mnt/b53c2b12-0aed-4083-aefc-7c4cb0046360/docker/containers/dd145bb873863187e1d3e508e475d36a65dddc8fb1fb8f4c74818e066169ff5d/hosts",
    "Id": "dd145bb873863187e1d3e508e475d36a65dddc8fb1fb8f4c74818e066169ff5d",
    "Image": "bd58cf964c1b13de2a89cd7b6b14a15fb49f2780b07d136a7cd6bb7a93611bf4",
    "LogPath": "/mnt/b53c2b12-0aed-4083-aefc-7c4cb0046360/docker/containers/dd145bb873863187e1d3e508e475d36a65dddc8fb1fb8f4c74818e066169ff5d/dd145bb873863187e1d3e508e475d36a65dddc8fb1fb8f4c74818e066169ff5d-json.log",
    "MountLabel": "",
    "Name": "/desperate_perlman",
    "NetworkSettings": {
        "Bridge": "docker0",
        "Gateway": "172.17.42.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "172.17.0.8",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "LinkLocalIPv6Address": "fe80::42:acff:fe11:8",
        "LinkLocalIPv6PrefixLen": 64,
        "MacAddress": "02:42:ac:11:00:08",
        "PortMapping": null,
        "Ports": {
            "9200/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "32780"
                }
            ],
            "9300/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "32781"
                }
            ]
        }
    },
    "Path": "/docker-entrypoint.sh",
    "ProcessLabel": "",
    "ResolvConfPath": "/mnt/b53c2b12-0aed-4083-aefc-7c4cb0046360/docker/containers/dd145bb873863187e1d3e508e475d36a65dddc8fb1fb8f4c74818e066169ff5d/resolv.conf",
    "RestartCount": 0,
    "State": {
        "Dead": false,
        "Error": "",
        "ExitCode": 0,
        "FinishedAt": "0001-01-01T00:00:00Z",
        "OOMKilled": false,
        "Paused": false,
        "Pid": 5361,
        "Restarting": false,
        "Running": true,
        "StartedAt": "2015-09-04T13:18:56.21906321Z"
    },
    "Volumes": {
        "/usr/share/elasticsearch/data": "/mnt/b53c2b12-0aed-4083-aefc-7c4cb0046360/docker/vfs/dir/66947008e712e3dc0eb153f717a16c35685d1962bb5f74db0df0dc91af2c54b0"
    },
    "VolumesRW": {
        "/usr/share/elasticsearch/data": true
    }
}
]

The response parser should use "no" as the default value.
By the way that doesn't seem to be present in Docker.DotNet.Models.RestartPolicyKind at the moment?

Requests Are Ignored

Hi,
Probably not the best place to ask this, but here it goes anyway...
I have a working installation of Docker, which I am trying to control with Docker.DotNet. The problem is, try as I might, I can't get any of the calls to return anything, but I also don't get any exceptions!
My basic code is:

var client = new DockerClientConfiguration(new Uri("tcp://192.168.99.100:2376")).CreateClient();
var containers = await client.Containers.ListContainersAsync(new ListContainersParameters());

I am monitoring the docker.log file, and I can see that no request gets there. Using the command line, everything works perfectly.
What can I be doing wrong?

Thanks!

RP

Capture Output of Newly Created Container

Hi,
For starting a new container and obtaining its output, I follow this workflow:

  • CreateContainerAsync(id) (returns containerId)
  • StartContainerAsync(id)
  • GetContainerLogsAsync(containerId)

Am I doing it right or is there a better way? Specifically, how can I use the AttachStdout and AttachStderr parameters of the Config parameter of CreateContainerParameters?

Thanks!

LogConfig property not available?

First of all, thanks for this great library. I'm trying to set some LogOptions within CreateContainerParameters. However, the CreatContainerParameters.Config.HotConfig.LogConfig property does not appear to be exposed, even though I see it in the source code.

I am using NuGet package version 1.2.2 according to NuGet package manager in VS. When I right-click and go to properties on the Docker.DotNet reference, it says version 1.0.0.0. I also don't see the "LogFile" property on the HostConfig class in the object browser. Is it possible NuGet somehow installed the wrong version? When I go into the package manager, it still says v1.2.2.

Docker Exec

Hi,
Am I right to assume that right now it isn't possible to use the Docker EXEC command with Docker.DotNet?
Thanks!
RP

GetSystemInfoAsync NetIPNet deserialization error

Hello,

Running GetSystemInfoAsync on a fresh docker install (version: 1.12.1, API version: 1.24) crashes with the following error:

Error converting value "127.0.0.0/8" to type 'Docker.DotNet.Models.NetIPNet'. Path 'RegistryConfig.InsecureRegistryCIDRs[0]', line 1, position 1046.

I'm using the latest Docker.DotNet code 6a3fa67

X509 not suport DNXcore

I trying install the library Docker.DotNet.X509 on my ASP.NET Core project, but VS it's displaying the mensage 'NU1002 The dependency Docker.DotNet.X509 1.2.2 in project does not support framework DNXCore,Version=v5.0.'

How i can fix this? or is a bug?

Regards

Unable to connect through DockerClient

Following is the code file I have behind an asp.net page:
public async Task<IList> list_containers()
{
var dockerConfiguration = new DockerClientConfiguration("192.xxx.xxx.xxx:8000");
DockerClient client = dockerConfiguration.CreateClient();

    this.containers_list = await client.Containers.ListContainersAsync(new ListContainersParameters()
                                                                                                    {
                                                                                                        All = true
                                                                                                    });
    return this.containers_list;
}

This container list variable doesnt get executed and I get the error (if i download the repository to the project, using nuget doesnt load the page and gives the error: "An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll but was not handled in user code

Additional information: An error occurred while sending the request."):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.xxx.xxx.xxx:8000; and the source error:
HttpResponseMessage response = await MakeRequestInnerAsync(null, HttpCompletionOption.ResponseContentRead, method, path, queryString, null, data, cancellationToken).ConfigureAwait(false);
As i debugged further, I see that the issue is around the result of MakeInnerRequestAsync: return _client.SendAsync(request, completionOption, cancellationToken), wherein the status of the response is at "WaitingForActivation". Suggestions as to how to get around this error? Any help would be great, as this had been working until about 2 weeks ago and now it returns this error.

.NET 2.0 support?

I notice TargetFrameworkVersion is v4.0.

I'm wondering if this would work on .NET 2?

Cheers

Support run with --rm option

Docker allows starting new instances with the --rm option; what it does is, after the container execution ends, the container is removed.
If there is interest, I can submit a pull request.

Some of the timeout style properties should be TimeSpan

For example:

Config.StopTimeout
HealthConfig.Interval
HealthConfig.Timeout
etc.

This will require us to implement custom JsonConverters for TimeSpan but because sometimes the result is in Seconds and in others its NanoSeconds we likely need to introduce an attribute that describes the destination conversion expected.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.