
When creating a container using the docker run command, the -p or --publish option can be used to declare the ports that will be used between the Docker server and the container, which adds a rule to iptables to allow the port.
In this example, a container is created using the my-image:latest image, and the Docker server will listen on port 8080 and the container will listen on port 1337.
docker run --publish 8080:1337 --name my-container my-image:latest
If you do you include the IPv4 or IPv6 address, and you only declare the ports, the container will listen on both IPv4 and IPv6, which can be seen with the docker ls command.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
d937372c09ab9 b939aa938add9913 "/docker-entrypoin..." 6 minutes ago Created 0.0.0.0:9000->9000/tcp, ::8080->1337/tcp my-container
By simply include 0.0.0.0 or and the IP address or hostname on the Docker system, the container will only be listed on IPv4.
docker run --publish 0.0.0.0:8080:1337 --name my-container my-image:latest
Of if the container already exists the docker update command can be used.
sudo docker update --publish 0.0.0.0:8080:1337 my-container
Which can be seen with the docker ls command.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS
d937372c09ab9 b939aa938add9913 "/docker-entrypoin..." 6 minutes ago Created 0.0.0.0:9000->9000/tcp my-container
Or you can use the docker inspect command to view the JSON for the container.
~]$ sudo docker inspect my-container | jq .[].HostConfig.PortBindings
{
"80/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "18089"
}
]
}
~]$ sudo docker inspect my-container | jq .[].NetworkSettings
{
"Bridge": "",
"SandboxID": "3bcbed81de9f0c6197e3b7866b875570aca0e7fea5b215dabda100dd878d1806",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {
"443/tcp": null,
"80/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "18089"
}
]
},
"SandboxKey": "/var/run/docker/netns/3bcbed81de9f",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "c2072a51155917302309744f69c76dfd71998b651e3eec4943a6f8e2fb706a76",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.15",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:05",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "4775001eae48c1887abc1c0f1bd1887a1b85aa7b49794b94509921e64e65bafc",
"EndpointID": "c2072a51155917302309744f69c76dfd71998b651e3eec4943a6f8e2fb706a76",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.15",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:05",
"DriverOpts": null
}
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at