This post has been specifically written for newbies who get very much confused with Docker Ports.
After hosting a couple of sessions to learn Docker with other fellow novices, I arrived at the conclusion that Docker Ports is something a lot of first-timers struggle with.
Let's begin with a basic Flask app:
Here the port specified is 8080, when you run this app on your local machine using the following command
$ python app.py
The flask app will be served on localhost 8080 which can be accessed using a web browser.
Now when we try to dockerize this flask app there will be two ports, one internal/container port and the other external/host port.
Consider the Dockerfile:
Dockerfile is like a recipe which very clearly specifies how the image should be built. We mention what base operating system image should be used, dependencies and libraries to be installed, commands to be run and all.
We first build the image using Docker build command and then run it using Docker run.
The general syntax of Docker build command is
$ docker build -t tagname .
The . at the end is important as this instructs Docker and tells it where your Dockerfile is located, in this case, it is the directory you are currently in.
Now we run the docker container
$ docker run -p 8000:8080 imagename Syntax : $ docker run -p [external port]:[internal port] imagename
-p refers to publishing. You can use -P as well.
Publishing ports creates a firewall rule which maps a container port to the outside world on the host port
Here Port 8000 is the external/host port and Port 8080 is the internal/container port because the flask app now runs from inside the container.
The above Docker run command would output:
* Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
Remember it is being served on localhost 8080 inside the container and on your local machine you need to run it on localhost 8000 i.e you external port.
Though there is no hard and fast rule but it is fairly a common practice to use same ports when using docker run:
$ docker run -p 8080:8080 image
This sometimes creates confusion among newbies in understanding which one is the external and internal port on local machine and inside the container.