I have docker running on my Windows 10 OS and I have a minimal flask app
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host ='0.0.0.0', port = 5001, debug = True)
And I am dockerizing it using the following file
FROM python:alpine3.7
COPY . /opt
WORKDIR /opt
RUN pip install -r requirements.txt
EXPOSE 5001
ENTRYPOINT [ "python" ]
CMD ["app.py", "run", "--host", "0.0.0.0"]
From what I am seeing on other posts and on Flask tutorials having a 0.0.0.0 should allow me to connect from the windows firefox browser when I type 0.0.0.0:5001 but it is not connecting, I keep getting a 'unable to connect' message. I remember using the 0.0.0.0:port to connect in localhost on a linux ubuntu machine but for whatever reason its not letting me connect on Windows. Is there a special setting to connect on windows ?
Inside the Docker container, the private port is 5001. This private port then needs to be mapped to a public port when running the container. For example, to set the public port to 8000, you could run:
$ docker run --publish 8000:5001 --name <docker-container> <docker-container>:<version-tag>
The Flask app would then be accessible at URL: http://127.0.0.1:8000
Dockerfile
In addition, since in app.py you are setting the host and port, there is no need to specify these values in the Dockerfile CMD. But the public port (in this example 8000) needs to be exposed.
It also looks like the COPY command is placing everything under an /opt directory, so that needs to be included in the app path when launching the Flask app within Docker.
FROM python:alpine3.7
COPY . /opt
WORKDIR /opt
RUN pip install -r requirements.txt
EXPOSE 8000
CMD ["python", "/opt/app.py"]
Docker-Flask Example
For a complete Flask-Docker example, including using Gunicorn, see:
Docker Python Flask Example using the Gunicorn WSGI HTTP Server
Related
I am trying to run a flask app using a docker.
Operating system Windows 11, WSL image Ubuntu-20.04.
A simple reproducible example:
https://github.com/Konrad-H/stackoverflow-question
If I run (inside a venv)
$ python app/main.py
the following message appears in the console:
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
And I can successfully connect to the app.
On the other hand, if I try to run the repo using:
$ docker build -t s-o-question:latest .
$ docker run -p 5000:5000 s-o-question
I get the exact same message on the console, but the webpage takes a long time loading and after a while a connection timeout appears.
The error appears both inside WSL2 and inside Windows.
Source Code:
main.py
import logging
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def index():
print("Hello World I am Sea")
return "Hello big world"
if __name__ == "__main__":
app.logger = logging.getLogger("audio-gui")
app.run( host='0.0.0.0',port=5000, debug=True)
Dockerfile
FROM python:3.8
# Working Directory
WORKDIR /app
# Copy source code to working directory
COPY . ./app /app/
# Install packages from requirements.txt
# hadolint ignore=DL3013
RUN pip install --no-cache-dir --upgrade pip &&\
pip install --no-cache-dir --trusted-host pypi.python.org -r requirements.txt
EXPOSE 5000
ENTRYPOINT [ "python" ]
CMD [ "app/main.py" ]
I had the same issue. The URL http/localhost:5000/ worked for me (5000 is my exposed port number). you can try and see if it works. Alternatively, you can also try http://<host-ip>:5000/. Note that the host-ip should be IP address of your local machine not the IP address of the docker container.
you can also check this answer
The issue is that you cannot use same port number for ex if your app runs on port 5000 it must be bind to another port like 8080 in docker .
try this docker run -p 8080:5000 s-o-question
I had the same issue on my win 11 device , i worked around this using the above solution.
I am trying to run a flask through docker.
My dockerfile:
FROM python:3
# set a directory for the app
WORKDIR /usr/src/app
# copy all the files to the container
COPY . .
# install dependencies
RUN pip install --no-cache-dir -r requirements.txt
# tell the port number the container should expose
EXPOSE 3000
# run the command
ENTRYPOINT ["python", "app.py"]
My app.py
import os
from flask import Flask, request, jsonify
from submission import SubmissionResult
app = Flask(__name__)
#app.route("/health")
def health_check():
return "healthy"
if __name__ == "__main__":
app.run(debug=True)
I ran docker run <my_image>.
When I hit "/health" on postman, I get an error saying:
Could not get any response
There was an error connecting to .
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General
It's weird because my flask app doesn't show any debugging logs, so presumably the request isn't hitting the server. Am I not exposing the port correctly?
How do I fix this?
You are not specifying the output port on the Python code. It maps to the default port, which is 5000. Use app.run(debug=True, port=3000) if you want to expose to port 3000. You also have to export the Docker port on host, do this calling -p 3000:3000 before <my_image>. It will tell Docker to map port 3000 of the image to port 3000 of host.
I am newbie to Docker and Python.I have created a simple python application using Flask .I would like to run it in a Docker container.The docker container shows it is running.However when I access the url ,I get localhost didn’t send any data.
docker container ls shows my container running on localhost and port no 8081
app.py
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
#app.route("/hello", methods=["GET","POST"])
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True, port=8081,host='0.0.0.0')
Dockerfile
FROM python:2.7
ADD app.py /
RUN pip install flask
EXPOSE 8081
CMD ["flask", "run", "--host=0.0.0.0"]
CMD ["python", "app.py", "--host=0.0.0.0"]
When I run the same app.py in my local environment.I get the desired data on the localhost url. Could someone guide me in the right direction?
Image is tagged dockerimage:latest and I run it with:
docker run -it -p 8081:8081 dockerimage
And checking for the container with docker container ls shows:
0.0.0.0:8081->8081/tcp
Everything seems fine in your Dockerfile and the Flask script, but I will suggest two thing.
Update base image to python:3.7 as 2.7 will reach its end of life.
Remove CMD ["flask", "run", "--host=0.0.0.0"] this as there is only one CMD per dockerfile.
FROM python:3.7.4-alpine3.10
RUN pip install flask
ADD app.py /
EXPOSE 8081
CMD ["python", "app.py", "--host=0.0.0.0"]
Now run the container
docker run -it --name my_app --rm -p 8081:8081 dockerimage
Open the browser and hit
http://localhost:8081/hello
or
docker exec -it my_app ash -c "apk add --no-cache curl && curl localhost:8081/hello"
One of the above should work.
If you the second command work then something wrong with host configuration.
I have created a simple flask app that is running on a this is the skeleton o the flask app, which by default runs at port 5000:
# Create the application instance
app = connexion.App(__name__, specification_dir="./")
# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")
# Create a URL route in our application for "/"
#app.route("/")
def home():
"""
This function just responds to the browser URL
localhost:5000/
:return: the rendered template "home.html"
"""
return render_template("home.html")
if __name__ == "__main__":
app.run(debug=True)
In the Dockerfile I'm exposing the same port:
RUN python3 -m pip install -r requirements.txt
COPY . /app
EXPOSE 5000
Then I run the container as:
sudo docker run -d -p 5000:5000 my_app:latest
and once the container is up, I'm able to acces to app at:
http://localhost:5000
Now, I'm trying to change to port 5100, for that I'm changing:
a) In the Dockerfile:
COPY . /app
EXPOSE 5100
...
b) When I run the container:
sudo docker run -d -p 5100:5100 my_app:latest
But when I try to visit: http://localhost:5100/
The app is not running there
When I do Docker ps this is shown:
EDIT:
I tried changing the flask app:
app.run(host='0.0.0.0', port=5100)
Still not working, this is the screenshot from docker ps:
Not sure if the error is because still says 5000: at the begining:
5000/tcp, 0.0.0.0:5100->5100/tcp romantic_fermi
This is what I get from docker logs...
* Serving Flask app "server" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
You could technically change the default port assigned to the Flask object, but it's simpler to just change the docker mapping.
When you run a command like this:
$ docker run -d -p 5100:5100 my_app:latest
You are saying that you want to forward a port from inside the container (on the right) to your host machine (on the left).
# Left side is your host machine
# Right side is inside of the container
5100:5100
So you could update your run to map to 5000 inside of the container:
$ docker run -d -p 5100:5000 my_app:latest
Then you'll be able to access via http://localhost:5100
PS: If you haven't used docker-compose before, I would highly recommend setting it up after you've worked through this issue. It'll make your life easier in general.
On your .py script ou need to set 5100 port with:
app.run(debug=True,host='0.0.0.0', port=5100)
Everything else you did is correct!
If still your python are listening on port 5000, probably it's the old version.
I am looking build a simple web application using Flask, Docker, and Google Container Engine. I have specified the following DockerFile:
# Use an official Python runtime as a base image
FROM python:2.7-slim
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 8080
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
Note I am exposing port 8080.
Here is my simple Flask application:
from flask import Flask, jsonify
from flask import make_response
app = Flask(__name__)
tasks = [
{
'type': 'order',
'contents':[1,2,3,4,5,6,7,8,9,10]
}
]
#app.route('/', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
#app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Note host='0.0.0.0' and port=8080.
I run the docker container locally, successfully:
docker run --rm -p 8080:8080 gcr.io/${PROJECT_ID}/hello-node:v1
However, when I deploy the application using the Google Container Engine I am not able to access the application via the external port provided by kubectl get service.
I run the following to deploy a Pod:
kubectl run hello-world --image=gcr.io/${PROJECT_ID}/hello-node:v1 --port 8080
I run the following commands to create a Service to access from the internet:
kubectl expose deployment hello-world --type=LoadBalancer --port 8080
Why am I not able to access the service? It seems I have opened port 8080 within every step 1) Flask application 2) Dockerfile 3) Pod Deployment 4) Service creation.
I think you should point out the target port as well when exposing your deployment, like this:
kubectl expose deployment hello-world --type=LoadBalancer --port=8080 --target-port=8080
Hope it helps