Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a port to a host interface using the REST API

Tags:

docker

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.

like image 918
Pickels Avatar asked Dec 06 '13 16:12

Pickels


2 Answers

This is an undocumented feature. I found my answer on the mailing list:

When creating the container you have to set ExposedPorts:

"ExposedPorts": { "22/tcp": {} }

When starting your container you need to set PortBindings:

"PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }

There already is an issue on github about this.

like image 153
Pickels Avatar answered Nov 03 '22 07:11

Pickels


Starting containers with PortBindings in the HostConfig was deprecated in v1.10 and removed in v1.12.

Both these configuration parameters should now be included when creating the container.

POST /containers/create

{
    "Image": image_id,
    "ExposedPorts": {
        "22/tcp": {}
    },
    "HostConfig": {
        "PortBindings": { "22/tcp": [{ "HostPort": "" }] }
    }
}
like image 37
James Thomas Avatar answered Nov 03 '22 06:11

James Thomas