我有一个深度学习模型,我用flask部署了它,当我通过邮递员发送发布请求时,它可以完美地工作,我将应用程序容器化在docker中,docker看起来可以正常运行,但是主机始终无法访问。任何帮助将不胜感激,谢谢!
我尝试更改端口号等EXPOSE 5000,我使用docker run -p 5000:5000“ name”运行了docker。似乎没有任何作用。
这是docker文件-
FROM python:3.6
RUN pip3 install opencv-contrib-python-headless
COPY ./flask_code.py /deploy/
COPY ./requirements.txt /deploy/
COPY ./ResNet50_model_weights.h5 /deploy/
WORKDIR /deploy/
RUN pip3 install -r requirements.txt
ENTRYPOINT ["python", "flask_code.py", "production"]
这是我的flask_code.py
from io import BytesIO
import pickle
import numpy as np
from flask import Flask, request
import pandas as pd
import tensorflow as tf
import keras
from keras.models import load_model
from keras.models import model_from_json
import os
import cv2
from PIL import Image
import base64
model = None
app = Flask(__name__)
def readb64(base64_string):
sbuf = BytesIO()
sbuf.write(base64.b64decode(base64_string))
pimg = Image.open(sbuf)
return cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR)
def load_model_flask():
global model
# model variable refers to the global variable
model = load_model("ResNet50_model_weights.h5")
@app.route('/')
def home_endpoint():
return 'Hello World!'
@app.route('/predict', methods=['POST'])
def get_prediction():
# Works only for a single sample
if request.method == 'POST':
data = request.get_json() # Get data posted as a json
print(data['string'][:5])
gray = readb64(data['string'])
print(gray.shape)
gray = cv2.resize(gray, (300,300), interpolation = cv2.INTER_AREA)
print("after", gray.shape)
gray = np.expand_dims(gray, axis=0)
print(gray.shape)
pred = model.predict(gray)
#print(pred)
#data = np.array(data)[np.newaxis, :] # converts shape from (4,) to (1, 4)
#prediction = model.predict(data) # runs globally loaded model on the data
print("The class of this garbage is:")
index = np.argmax(pred[0],axis = 0)
return str(index+1)
if __name__ == '__main__':
load_model_flask() # load model at the beginning once only
app.run(host='127.0.0.1',debug = False, threaded = False)
Flask_code.py单独运行时工作正常。
我希望转到http://127.0.0.1:5000/时会收到“ hello world”消息相反,它说“连接已重置”
app.run(host='127.0.0.1',debug = False, threaded = False)
您正在将应用程序与容器的本地主机绑定,这就是为什么无法从主机访问它的原因。也更改此内容
app.run(host='0.0.0.0',debug = False, threaded = False)
因此,它将可以从主机访问。