Docker.DotNet icon indicating copy to clipboard operation
Docker.DotNet copied to clipboard

How do I publish a random port?

Open baautitz opened this issue 1 year ago • 1 comments

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", [] }
        }
    }
};

baautitz avatar May 17 '24 16:05 baautitz

Bump this - anyone have a solution to this? Currently dealing with this issue as well.

wfahnestock avatar May 02 '25 22:05 wfahnestock

Simply set the HostPort property of the PortBinding type to an empty string. Like we are doing in Testcontainers.

HofmeisterAn avatar May 03 '25 07:05 HofmeisterAn

Simply set the HostPort property of the PortBinding type to an empty string. Like we are doing in Testcontainers.

The empty is not working for this version with Docker.DotNet (3.125.15) Docker version 28.1.1, build 4eba377

var portBinding = new PortBinding
                      {
                          // HostPort = "0/tcp" // working on Docker version <=28.1.1
                          HostPort = string.Empty // working on Docker version >=28.2.2
                      };

mm-ryo avatar Jun 20 '25 07:06 mm-ryo