Binding a port to a host interface using the REST API

Viewed 15202

The documentation for the commandline interface says the following:

To bind a port of the container to a specific interface of the host system, use the -p parameter of the docker run command:

General syntax

docker run -p [([<host_interface>:[host_port]])|(<host_port>):]<container_port>[/udp] <image>

When no host interface is provided, the port is bound to all available interfaces of the host machine (aka INADDR_ANY, or 0.0.0.0).When no host port is provided, one is dynamically allocated. The possible combinations of options for TCP port are the following

So I was wondering how I do the same but with the REST API?

With POST /container/create I tried:

  • "PortSpecs": ["5432:5432"] this seems to expose the port but not bind it to the host interface.
  • "PortSpecs": ["5432"] gives me the same result as the previous one.
  • "PortSpecs": ["0.0.0.0:5432:5432"] this returns the error Invalid hostPort: 0.0.0.0 which makes sense.

When I do sudo docker ps the container shows 5432/tcp which should be 0.0.0.0:5432/tcp.

Inspecting the container gives me the following:

"NetworkSettings": {
    "IPAddress": "172.17.0.25",
    "IPPrefixLen": 16,
    "Gateway": "172.17.42.1",
    "Bridge": "docker0",
    "PortMapping": null,
    "Ports": {
        "5432/tcp": null
    }
}

Full inspect can be found here.

3 Answers

I know this question had been answered, I using the above solution and here is how I did it in java using Docker Java Client v3.2.5

    PortBinding portBinding = PortBinding.parse( hostPort + ":" + containerPort);
    HostConfig hostConfig = HostConfig.newHostConfig()
            .withPortBindings(portBinding);
    CreateContainerResponse container =
            dockerClient.createContainerCmd(imageName)
                    .withHostConfig(hostConfig)
                    .withExposedPorts(ExposedPort.parse(containerPort+"/tcp"))
                    .exec();
Related