I’m trying to run a Flask app in a docker container and connect to it using my browser. I am not able to see the app and get an error This site can’t be reached when trying to go to http://127.0.0.1:5000. I’ve already followed the advice in these two questions (1) (2).
This is my Dockerfile:
FROM python:3.11.5-bookworm
WORKDIR /app
COPY requirements.txt .
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["flask", "run", "--host", "0.0.0.0"]
and this is my app:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return 'hello'
if __name__ == "__main__":
app.run(host="0.0.0.0")
When I use docker desktop, I can see that the app is running correctly inside the docker container:
2023-09-27 14:14:44 * Debug mode: off
2023-09-27 14:14:44 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
2023-09-27 14:14:44 * Running on all addresses (0.0.0.0)
2023-09-27 14:14:44 * Running on http://127.0.0.1:5000
2023-09-27 14:14:44 * Running on http://172.17.0.5:5000
2023-09-27 14:14:44 Press CTRL+C to quit
2023-09-27 14:15:14 127.0.0.1 - - [27/Sep/2023 19:15:14] "GET / HTTP/1.1" 200 -
from the command line in the docker terminal, the output is also as expected:
# curl http://127.0.0.1:5000
hello#
However, when I use my browser to go to localhost (http://127.0.0.1:5000), I get an error: This site can’t be reached
In the tutorial I was watching, it worked, so I’m not sure what I’m doing wrong here…
>Solution :
Make sure to run the container specifying the mapping port:
docker run -p 5000:5000 <docker_image_id>
The first port stands for the port on the host machine, and the second one is for which port you want to map it in the container.
Make sure there aren’t any background processes running.
Check for any ( linux ):
netstat -tuln | grep 5000
If any found, kill:
kill -9 <PID>