HelloWorld-1.py
app = Flask(__name__)
#app.route('/')
def printHelloWorld():
print("+++++++++++++++++++++")
print("+ HELLO WORLD-1 +")
print("+++++++++++++++++++++")
return '<h1>Bishwajit</h1>'
# return '<h1>Hello %s!<h1>' %name
if name == '__main__':
app.run(debug='true')
Dockerfile
FROM python:3
ADD HelloWorld-1.py /HelloWorld-1.py
RUN pip install flask
EXPOSE 80
CMD [ "python", "/HelloWorld-1.py"]
Building docker using the below command
docker build -t helloworld .
Running docker image using below command
docker run -d --name helloworld -p 80:80 helloworld
when i run the below command
docker ps -a
i get the below output
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
cebfe8a22493 helloworld "python /home/HelloW…" 2 minutes ago Up 2 minutes (unhealthy) 0.0.0.0:80->80/tcp helloworld
If I hit in the browser(127.0.0.1:5000), it does not give response,
But when i run the python file individually, it runs properly in the browser.
I reproduced your problem and there were four main problems:
Not importing flask.
Using name instead of __name__
Not assigning the correct port.
Not assigning the host.
This is how your HelloWorld-1.py should look like:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def printHelloWorld():
print("+++++++++++++++++++++")
print("+ HELLO WORLD-1 +")
print("+++++++++++++++++++++")
return '<h1>Bishwajit</h1>'
# return '<h1>Hello %s!<h1>' %name
if __name__ == '__main__':
app.run(host='0.0.0.0')
This is how you Dockerfile should look like:
FROM python:3
ADD HelloWorld-1.py .
RUN pip install flask
CMD [ "python", "/HelloWorld-1.py"]
Then simply build and run:
docker build . -t helloflask
docker run -dit -p 5000:5000 helloflask
Now go to localhost:5000 and it should work.
Additionally: You could actually assign any other port, for example 4444, and then go to localhost:4444:
docker run -dit -p 4444:5000 helloflask
Related
The app is running locally but when i build docker image and try to run the app from local docker then the browser shows the following error:
This site can’t be reached http://172.17.0.2:8080/ is unreachable.
ERR_ADDRESS_UNREACHABLE and also taking too long to respond
what changes should i make in docker file or in the app code so that i can run it form local docker
Flask App code:
from flask import Flask,request, url_for, redirect, render_template, jsonify
from pycaret.regression import *
import pandas as pd
import pickle
import numpy as np
app = Flask(__name__)
model = load_model('deployment_28042020')
cols = ['age', 'sex', 'bmi', 'children', 'smoker', 'region']
#app.route('/')
def home():
return render_template("home.html")
#app.route('/predict',methods=['POST'])
def predict():
int_features = [x for x in request.form.values()]
final = np.array(int_features)
data_unseen = pd.DataFrame([final], columns = cols)
prediction = predict_model(model, data=data_unseen, round = 0)
prediction = int(prediction.Label[0])
return render_template('home.html',pred='Expected Bill will be{}'.format(prediction))
if __name__ == '__main__':
app.run(debug=True, port=8080, host='0.0.0.0')
Docker file:
FROM python:3.7
RUN pip install virtualenv
ENV VIRTUAL_ENV=/venv
RUN virtualenv venv -p python3
ENV PATH="VIRTUAL_ENV/bin:$PATH"
WORKDIR /app
COPY requirements.txt requirements.txt
ADD . /app
# install dependencies
RUN pip install -r requirements.txt
COPY . .
# expose port
# EXPOSE 5000
# EXPOSE 8000
EXPOSE 8080
# run application
CMD ["python", "app.py", "--host=0.0.0.0"]
Add a docker-compose.yml file
version: "3"
services:
app:
build: .
ports:
- "8080:8080"
Run: docker-compose up --build
An important thing to notice is that 172.17.0.2 belongs to your container network. You can access your site on
http://localhost:8080.
I am unable to rum Docker Container Registry on the Azure App service. I have a flask app and the following is the Dockerfile of it:-
FROM python:3.8-slim-buster
WORKDIR /usr/src/app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# copy project
WORKDIR /usr/src/app
COPY . /usr/src/app/
# expose port 80
EXPOSE 80
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:80", "app:app"]
I have deployed the docker image on the Container Registry. I have also set WEBSITES_PORT to 80 under App Service -> Application Settings.
Even after doing that, I get the following error:-
ERROR - Container XYZ didn't respond to HTTP pings on port: 80, failing site start.
I have tried running it locally and it works fine. But, it just does not seem to work on the Azure App service. Any help is highly appreciated.
I don't see an issue in the code you posted but to verify, here is a configuration for a Flask app with a Gunicorn server that works on a containerized Azure App Service:
app.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello_world():
return "<p>Hello World!</p>"
Dockerfile
FROM python:3.8-slim-buster
ADD app.py app.py
ADD requirements.txt requirements.txt
RUN pip install --upgrade pip
RUN python3 -m pip install -r requirements.txt
EXPOSE 80
CMD ["gunicorn", "--bind=0.0.0.0:80", "app:app"]
requirements.txt
flask
gunicorn
I assume you selected "Docker Container" when you created the Azure App Service?
And then simply chose your image?
I made a test flask application that looks like the following:
from flask import Flask
from flask_cors import CORS
import os
app = Flask(__name__)
CORS(app)
#app.route('/')
def hello_word():
return 'hello', 200
if __name__ == '__main__':
app.run(threaded=True, host='0.0.0.0', port=int(os.environ.get("PORT", 8080)))
However, if i host this application on Azure Container Instance, the application never "stops". The memory usage is always at around 50mb and I'm constantly getting charged. If I host the same application on Google Cloud run, I'm only charged for the request time (20ms or so). The following is my dockerfile
FROM python:3.9-slim
RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
RUN pip install Flask gunicorn
ENV PORT=80
CMD exec gunicorn --bind :$PORT --workers 3 --threads 3 --timeout 100 main:app --access-logfile -
Any thoughts on how to stop the container instance once the request is served on Azure?
Actually, the ACI just run the image for you and nothing else. It means if your image has an application that keeps running, then the ACI keeps running. And it seems you need to schedule to stop the ACI, maybe you can try the Azure logic App. You can use it to create the ACI and then stop it after a period that you need.
I am trying to make a Flask framework with python and trying to host it on Docker.
#importing dependencies
from flask import Flask
#initializing the name of the application
app = Flask(__name__)
#app.route('/')
def hello(parameter_list):
return 'Hello, this is my first try on Docker'
if __name__ == "__main__":
app.run(host="0.0.0.0", debug= True)
I am getting at Line 5 that name 'app' is not defined
what should i do to remove this error?
this is my first time asking a question over here, Please let me know if any other clarification is needed or suggestions for future posts.
Thanks in advance
The error you have shown in the image and the code does not seem matched. to reproduce your error is to pass app to flask object instead of __name__.
Here you go with HelloWorld
FROM python:alpine3.7
RUN pip install flask==0.10.1
COPY . /app
WORKDIR /app
EXPOSE 5000
CMD python app.py
and app.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Welcome to the Data Science Learner!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int("5000"), debug=True)
build
docker build -t flask-test .
run
docker run -it --rm flask-test
You can use the same with Docker compose,
docker-compose rm -f && docker-compose up --build
Summary
docker run doesn't seem to build a container (but it also doesn't throw an error) despite docker build successfully building the container image.
Input and Output
1. Successful docker image creation..
$ docker build -t minitwitter:latest .
...
Successfully built da191988e0db
Successfully tagged minitwitter:latest
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
minitwitter latest da191988e0db 6 seconds ago 173MB
python 3.7-alpine b11d2a09763f 9 days ago 98.8MB
2. ..and docker run completes without error..
$ docker run --name minitwitter -d -p 8000:5000 --rm minitwitter:latest
e8835f1b4c72c8e1a8736589c74d56ee2d12ec7bcfb4695531759fb1c2cf0e48
3. ..but docker container doesn't seem to exist.
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
And navigating to the port where the app should be exposed, http://localhost:8000, returns the connection error ERR_CONNECTION_REFUSED.
Docker file, boot.sh
The Dockerfile and boot.sh files are pretty simple I think:
Dockerfile
FROM python:3.7-alpine
RUN adduser -D minitwitter
WORKDIR /home/minitwitter
COPY requirements.txt requirements.txt
RUN python -m venv env
RUN env/bin/pip install -r requirements.txt
RUN env/bin/pip install gunicorn
COPY app app
COPY migrations migrations
COPY minitwitter.py config.py boot.sh ./
RUN chmod a+x boot.sh
ENV FLASK_APP minitwitter.py
RUN chown -R minitwitter:minitwitter ./
USER minitwitter
EXPOSE 5000
ENTRYPOINT ["./boot.sh"]
boot.sh
# BOOTS A DOCKER CONTAINER
#!/bin/sh
source env/bin/activate
flask db upgrade
exec gunicorn -b :5000 --access-logfile - --error-logfile - minitwitter:app
Place the 'shebang' -- #!/bin/sh -- on the first line of the boot.sh shell script.
How I found this answer: This blog post which refers to this Stackoverflow post.
The problem: the original script has a comment on the first line and the shebang on the second line.
Note: The title of the 'Question' is misleading: a docker container was built. The container, however, was short-lived and given I used the -rm option in the docker run command, the container was deleted after it terminated within 2 seconds; this is why it didn't appear in the docker images -a command.