Nick's Blog

Docker Explore Part 3 – Port Forwarding


From the part 2, we have set up Nginx and confirmed it’s running from the Dock process. In this post, I’m going to configure the port forwarding, so that we can check it from the browser.

Before we start to configure the port forwarding. We need to do a bit of clean up. Making sure that no docker process is running. Use docker kill [container id] to kill the existing process.

root@ip-172-31-11-57:/home/ubuntu# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d07c6a24bef0 nginx "nginx -g 'daemon off" 52 minutes ago Up 52 minutes 0.0.0.0:32768->80/tcp ecstatic_brahmagupta
root@ip-172-31-11-57:/home/ubuntu# docker kill d07
d07
root@ip-172-31-11-57:/home/ubuntu# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

Once we have done the clean up. we can run the docker run again. But this time we will add the port forward into the command.


As it returns the container id string, which means the command has been ran success. what we have done is forward the docker container 80 to the host 8080.

root@ip-172-31-11-57:/home/ubuntu# docker run -d -p 8080:80 nginx
32873cb9524e60223ade2e81e3b88c1a922d16f9861e39793e17ce692c76f71c

root@ip-172-31-11-57:/home/ubuntu# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
32873cb9524e nginx "nginx -g 'daemon off" 8 minutes ago Up 8 minutes 0.0.0.0:8080->80/tcp grave_shirley

So go to your host IP:8080. You will see the Nginx welcome page like below:

You also could forward the docker port to a random port of a host.

root@ip-172-31-11-57:/home/ubuntu# docker run -d -P nginx
7c8732f860e59d0bf45808b5c246a84267a500dfa0caed10b841b73f7f28d51c
root@ip-172-31-11-57:/home/ubuntu# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7c8732f860e5 nginx "nginx -g 'daemon off" 4 seconds ago Up 3 seconds 0.0.0.0:32769->80/tcp gloomy_liskov



So 8080 port should time out after the above command has been done. This time try to browse the high port 32769. You should get the same welcome page.