dotnet / Docker.DotNet

:whale: .NET (C#) Client Library for Docker API
https://www.nuget.org/packages/Docker.DotNet/
MIT License
2.23k stars 381 forks source link

How do I publish a random port? #678

Open baautitz opened 3 months ago

baautitz commented 3 months ago

I'm attempting to dynamically assign a random port to a container upon its creation. I've been experimenting with various configurations, including setting the PortBindings property to null and trying different values for HostPort such as 0, null, an empty string, and "0". However, I haven't been successful in achieving the desired outcome. Here's the snippet of code I've been working with:

CreateContainerParameters containerParameters = new CreateContainerParameters {
    Name = name,
    Image = type,
    HostConfig = new HostConfig {
        PortBindings = new Dictionary<string, IList<PortBinding>> {
            { "25565/tcp", [] }
        }
    }
};
hakimdotdev commented 3 months ago

Hi, this works for me:

var portBindings = new Dictionary<string, IList<PortBinding>>();
var exposedPorts = new Dictionary<string, EmptyStruct>();
portBindings.Add($"{hostport}/tcp", new List<PortBinding> { new() { HostPort = port.ToString() } });
exposedPorts.Add($"{port}/tcp", default);