Docker Tutorials: Working with Ports in Docker Containers

Port expose and publish has to happen when a container is created. Just stop the existing container and create a new one in its place with the added expose and/or publish options.

By default Docker containers can make connections to the outside world, but the outside world cannot connect to containers. Each outgoing connection will appear to originate from one of the host machine’s own IP addresses thanks to an iptables masquerading rule on the host machine that the Docker server creates when it starts:

[code]$ sudo iptables -t nat -L -n

target prot opt source destination
MASQUERADE all —[/code]

The Docker server creates a masquerade rule that lets containers connect to IP addresses in the outside world. If you want containers to accept incoming connections, you will need to provide special options when invoking docker run. There are two approaches.

How to map ports to containers?
Approach 1
First, you can supply -P or –publish-all=true|false to docker run
EXPOSE line in the image’s Dockerfile
–expose <port> commandline flag and maps it to a host port somewhere within an ephemeral port range.

Approach 2
Mapping can be specified explicitly using -p SPEC or –publish=SPEC option. It allows you to particularize which port on docker server – which can be any port at all, not just one within the ephemeral port range – you want mapped to which port in the container.

How to EXPOSE Port on running container?

Mehtod 1 – Using docker commit
Commit your current container to a new image and then do a docker run specifying the new port range and the new image name.

[code]$ docker stop containerID
$ docker commit containerID newImageName:tag
$ docker run -d –name db -p 8091-8094:8091-8094 -p 11210:11210 newImageName:tag[/code]

Method 2 – using iptables

[code]HOST> iptables -t nat -A DOCKER -p tcp –dport 443 -j DNAT –to-destination
HOST> iptables -t nat -A POSTROUTING -j MASQUERADE -p tcp –source –destination –dport https
HOST> iptables -A DOCKER -j ACCEPT -p tcp –destination –dport https[/code]

Docker Tutorials Fundamental To Advanced-2021 Crash Course:-

Rajesh Kumar
Follow me
Latest posts by Rajesh Kumar (see all)
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x