Docker image for Flask applicatno

Question:

when a run a simple flask application with a specified port(5888) from the console it is running well and is provided with a
URL: * Debugger PIN: 125-876-281
* Running on http://127.0.0.1:5888/ (Press CTRL+C to quit)

for the same application when I build a docker image and run using the comman : docker run -p 192.168.0.152:5888:5888 dock_test is is giving the
URL : *** Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://172.17.0.3:5000** with the different port(5000).

The main python file: app.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def index():
    return "running"

if __name__ == "__main__":

    app.run(debug=True,port=5888)

docker file: Dockerfile

FROM ubuntu
RUN apt update
RUN apt install python3-pip -y
RUN pip3 install Flask
COPY requirements.txt requirements.txt
ENV LISTEN_PORT=5888
EXPOSE 5888
RUN pip3 install -r requirements.txt 
WORKDIR C:UsershemanPycharmProjectsdock_testmain.py
COPY . .
ENV FLASK_APP=main.py
CMD ["python3","-m","flask","run","--host=0.0.0.0"]

Step-1: To build the image I’ve run : docker build -t dock_test .(it created the docker image well)

step-2: To run : docker run -d -p 5888:5888 dock_test
output: * Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://172.17.0.3:5000
why the port is changing to 5000 instead of 5888?

Answers:

I think you are missing the port number in the Dockerfile.

In your docker file, you are calling your application as a module (by using -m). When you run a module, it’s first imported internally and then runs the function inside it. You can find more details here: Execution of Python code with -m option or not

So basically, the if "____main___" part is skipped when you call using the -m command. Thus, the flask app is defaulting to the default port 5000. If you specify it in the Dockerfile, as shown below, it should work.

CMD ["python3","-m", "flask", "run","--host=0.0.0.0", "--port=5888"]
Answered By: Saurav Panda