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:

$ sudo iptables -t nat -L -n
target prot opt source destination

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.

$ docker stop containerID 
$ docker commit containerID newImageName:tag
$ docker run -d --name db -p 8091-8094:8091-8094 -p 11210:11210 newImageName:tag

Method 2 – using iptables

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
Tagged : / / /

Changing port of ftp and ssh

rajeshkumar created the topic: Changing port of ftp and ssh
Changing port of ftp and ssh
To Change the port of ssh, edit the file /etc/ssh/sshd_config and add the following line:

port 222

Restart the services of ssh to make the changes effective. Now you need to specify the port number using option ‘-p’ whenever you want to access this system.

# ssh localhost -p 22

In order to change the port of ftp server, edit the file /etc/vsftpd/vsftpd.conf

listen_port=2100 # # Add thus line

Restart the service of ftp

Now run the following command to check if the listening ports have been changed or not;

ftp localhost 2100

you can even check the open port using the netstat or nmap commands..
Rajesh Kumar
Twitt me @

Tagged :