Can't access my simple flask app running in docker [duplicate] - python

This question already has answers here:
Deploying a minimal flask app in docker - server connection issues
(8 answers)
Closed 1 year ago.
The app runs, but when I try to go to the link # http://172.17.0.2:5000/ it times out.
relevant code:
app = Flask(__name__)
#app.route('/')
def index():
return "hullo"
I have also tried it with and without this code underneath which is what other stackoverflow responses to questions similar to mine have suggested, but it doesn't work:
if __name__ == '__main__':
app.run(host ='0.0.0.0')
Dockerfile:
FROM python:3.9.6-slim-buster
WORKDIR /project
RUN python -m pip install --upgrade pip
RUN pip install -U Flask Flask-WTF Flask-SQLAlchemy DateTime python-dotenv mysql-connector-python
COPY . .
CMD [ "python3", "-m" , "flask", "run", "--host", "0.0.0.0"]
Run cmd:
docker run --publish 5000:5000 testbon5
This is practically copy and pasted from the official docs tutorial. Is there something I'm doing wrong?

figured it out. from a very nice person on slack.
I needed to type "localhost:/5000" into my address bar. It confused me because I have always access the site I'm working on through the flask log which in this case is:
* Serving Flask app 'project/app.py' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://172.17.0.2:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
I guess since it's running in the container that address doesn't work anymore. Hopefully this helps anyone else going through growing pains like me while learning docker.

Related

Flask auto-reload functionality not working with Pycharm Remote Deployment

It's hard to remember when, but at one point the auto-reload function of Flask started to not work anymore in my project.
This is the output upon starting my app :
FLASK_APP = back/python/app/app.py:app
FLASK_ENV = development
FLASK_DEBUG = 1
In folder C:/path/to/project
ssh://[VirtualMachineIP]:22/root/env/bin/python3.7 -u -m flask run -h 0.0.0.0 -p 1234
* Serving Flask app 'back/python/app/app.py:app' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://[VirtualMachineIP]:1234/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 106-048-128
The development environment and Debug mode are both on. Thus, upon saving changes in a file (while the app is deployed) I get the usual message :
* Detected change in '/path/to/changed/file.py', reloading
Signaling that the app is reloading with the new code. Except it doesn't reload anything, and the message doesn't appear on any further changes until I'm forced to restart the app.
PyCharms runs on Windows and communicates via ssh to my Virtual Machine, where the code is executed. I have installed the following modules:
flask
flask-socketio
eventlet
flask-cors
Any help is welcomed. Thanks :)
The FLASK_DEBUG environment variable is badly supported, it may not behave as expected if set in code. (Quoted from the source of flask).
It suggest to use flask run in debug mode.
eg: $ flask --app hello --debug run
If it still not work, you can force to use reloader like this:
if __name__ == '__main__':
app.run(host=config.HOST, port=config.PORT, debug=True)
Take care, the app.run() must be wrapped with if __name__ == '__main__'.
doc: https://flask.palletsprojects.com/en/2.2.x/config/#DEBUG

Docker: How do I debug localhost "Internal Server Error"?

First time using Docker(version 19.03.5) and trying this tutorial
I'm stuck on step 2.3.4 Running an image
When I go to http://localhost:8888 I see
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I updated Dockerfile to this to match my directory:
# our base image
FROM alpine:3.5
# Install python and pip
RUN apk add --update py2-pip
# install Python modules needed by the Python app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# copy files required for the app to run
COPY app.py .
COPY templates/index.html templates
# tell the port number the container should expose
EXPOSE 5000
# run the application
CMD ["python", "app.py"]
On my command line I have
C:\Users\user\docker\flask-app>docker run -p 8888:5000 --name flask-app 11111111/flask-app
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
When I visit the page I see on the prompt
172.17.0.1 - - [05/Jan/2020 07:14:34] "GET / HTTP/1.1" 500 -
I have this in my app.py
from flask import Flask, render_template
import random
app = Flask(__name__)
# list of cat images
images = [
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr05/15/9/anigif_enhanced-buzz-26388-1381844103-11.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr01/15/9/anigif_enhanced-buzz-31540-1381844535-8.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr05/15/9/anigif_enhanced-buzz-26390-1381844163-18.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr06/15/10/anigif_enhanced-buzz-1376-1381846217-0.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr03/15/9/anigif_enhanced-buzz-3391-1381844336-26.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr06/15/10/anigif_enhanced-buzz-29111-1381845968-0.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr03/15/9/anigif_enhanced-buzz-3409-1381844582-13.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr02/15/9/anigif_enhanced-buzz-19667-1381844937-10.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr05/15/9/anigif_enhanced-buzz-26358-1381845043-13.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr06/15/9/anigif_enhanced-buzz-18774-1381844645-6.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr06/15/9/anigif_enhanced-buzz-25158-1381844793-0.gif",
"http://img.buzzfeed.com/buzzfeed-static/static/2013-10/enhanced/webdr03/15/10/anigif_enhanced-buzz-11980-1381846269-1.gif"
]
#app.route('/')
def index():
url = random.choice(images)
return render_template('index.html', url=url)
if __name__ == "__main__":
app.run(host="0.0.0.0")
I can't figure out why my page isnt loading. Any help would be appreciated.
Note: I have WAMP installed and this might be conflicting but not sure if thats the case and/or how to fix it.
Flask might be unable to locate your templates. Try changing
COPY templates/index.html templates
to
COPY templates templates
to copy everything inside ./templates to <WORKDIR>/templates.
Using COPY templates/index.html templates will copy index.html as a file at path <WORKDIR>/templates, not copy it under that directory.
How to debug your Flask application in Docker:
Turn on Flask debugger by adding ENV FLASK_DEBUG=1 to your Dockerfile
Try to run the Flask app outside of Docker. It may be easier to set breakpoints inside your IDE (VSCode or PyCharm) and debug the app.
Try pdb to debug the app inside the container. It may be hard for a beginner, but in general, it's an essential skill. Check Debugging a Python Flask Application in a Docker Container for a step-by-step guide.
Note: This is more aimed at the question "How do I debug". It was unclear that the OP actually wanted a solution, not a way to solve the problem.
First thing to do is to start the container without the app in it. For that, you replace the CMD ["python", "app.py"] with CMD ["sleep", "inf"]. Now, after starting the container, you can get a shell in the container using docker exec -it flask-app /bin/bash to get a shell. In the shell, you can then use the regular Python debugger to set a breakpoint in the / handler and then single-step through the code to track down what Python's doing.

Running Flask in Docker Using Volumes Causes Error on Reload

I'm setting up my dev environment for a flask app in a docker container and during dev I want to be able to put Flask in development mode so that I can get live reloads when I change a file. I'm using volumes so that I can edit the files outside of docker. I am getting the desired behavior from Flask, on editing the flask test file it detects the file change, however, it appears to be attempting to serve trunkated files instead of the files as edited resulting in errors from the app.
Dockerfile:
FROM python:3.8.1-alpine3.11
RUN apk update && apk upgrade && apk add bash
#Set ENV Variables
ENV FLASK_APP hello.py
#Add user.
RUN adduser -D eskimotv
USER eskimotv
#Set Work directory
WORKDIR /home/eskimotv
#Install Dependencies
COPY requirements requirements
RUN python -m venv venv
RUN venv/bin/pip install --upgrade pip
RUN venv/bin/pip install -r requirements/docker.txt
#Copy project files
COPY frontend frontend
COPY migrations migrations
COPY boot.sh ./
#Deploy Project
EXPOSE 5000
#ENTRYPOINT ["./boot.sh"]
Docker-compose.yml:
version: '3'
services:
frontend:
image: bentsea/eskimotv-frontend:latest
build:
dockerfile: frontend.dockerfile
context: .
ports:
- "8000:5000"
env_file: .env
volumes:
- './boot.sh:/home/eskimotv/boot.sh'
- './hello.py:/home/eskimotv/hello.py'
- './frontend:/home/eskimotv/frontend'
#entrypoint: ./boot.sh
restart: always
Simple flask app, hello.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello World!</h1><p> Please work!</p>'
#app.route('/user/<name>')
def user(name):
return '<h1>Hello, {}!</h1>'.format(name)
Environtment variable FLASK_ENV is set to development. When starting up the app for the first time all my changes are displayed correctly:
If I make a very simple edit, such as changing line 10 of hello.py with a cosmetic change, such as the following:
return '<h1>Hello, {}, I made a small change to the text!</h1>'.format(name)
Flask will appropriately reload:
* Detected change in '/home/eskimotv/hello.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger PIN: 234-654-899
172.21.0.1 - - [31/Dec/2019 20:00:20] "GET /user/David HTTP/1.1" 200 -
* Detected change in '/home/eskimotv/hello.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger PIN: 234-654-899
However, the page will begin to produce an error rather than correctly display the page:
Sometimes it's just an EOL error that indicates that the file is truncated, sometimes it indicates this null error. Either restarting the Flask server or undoing the edits made to the file resolves the issue and the app will function normally. Restarting the server every time I make an edit is the action I was wanting to avoid.
Does anyone have any ideas what would cause the files in this volume configuration to load incorrectly and what I can do to resolve the issue to get the intended behavior of having the reload display the file as it is edited?
I don't know why the error is occurring, however it does appear to be caused by mounting a single file instead of a directory. By restructuring my app to mount only entire directories that include the files that need to be updated I was able to successfully use a workflow that allows for automatic Flask reload through Docker on file change.
For whatever reason Docker does not accurately update individual files that are mounted if they are outside of a mounted directory.
Try after you change your code to rebuild your docker.
Before making the change do
docker-compose stop
Then make the change by editing the line
return '<h1>Hello, {}, I made a small change to the text!</h1>'.format(name)
after making your change above, now do
docker-compose build
And finally
docker-compose up

ModuleNotFoundError: No module named 'verovio'

Hi there I would like to run my flask app in a container but I got stucked caused of a third party module. (I am using PyCharm)
This is my docker file:
FROM python:3-alpine
MAINTAINER foo
COPY app /app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python3", "gateway.py"]
I run the container by this command:
docker run --name mei_converter -p 5000:5000 mei_converter:latest
And receives this:
ModuleNotFoundError: No module named 'verovio'
I already fixed the dependencies in order to run it on my local machine
Terminal: python3 gateway.py
['/usr/local/lib/python3.7/site-packages',
'/Users/max/PycharmProjects/flaskmicroservice/app',
'/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-
dynload', '/Users/max/Library/Python/3.7/lib/python/site-packages',
'/usr/local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages/verovio-
2.0.0-py3.7-macosx-10.13-x86_64.egg']
* Serving Flask app "gateway" (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:5000/ (Press CTRL+C to quit)
This works well
I also checked the project interpreter in PyCharm and found the package as installed.
Maybe some information about this third party package could help:
It is a converter for music-encoding from these guys https://www.verovio.org/python.xhtml
and not "native python" (SWIG is necessary)
By the way.. I come from the java world and have in fact zero experience with python. I am using this flask app as an microservice for my spring boot app.
I would be grateful for any help!
You need to do in the container the same you did in your local host. That is, you need to add steps to the Dockerfile to compile verovio and use it in the container.

Unable to load python flask API with a docker container

I'm trying to learn Docker containers with APIs. I have created a simple Hello World python REST API with flask:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run(host="127.0.0.1", debug=True, port=8080)
This works when I run the script and go to http://localhost:8080/
This is my Dockerfile:
# Use an official Python runtime as a parent image
FROM python:2.7-slim
# Set the working directory to /app
WORKDIR /hello_world
# Copy the current directory contents into the container at /app
ADD . /hello_world
# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
EXPOSE 8080
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "hello_world.py"]
requirements.txt:
Flask
My current directory contains Dockerfile, hello_world.py and requirements.txt.
I can successfully build the image with docker build -t hello_world ."
Running it with docker run -p 8080:8080 -t hello_world gives me the following output:
Serving Flask app "hello_world" (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://127.0.0.1:8080/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 985-433-141
When I try going to http://127.0.0.1:8080/ I get the "Can't reach this page" error. Do you know what I'm doing wrong? Thank you.

Categories

Resources