我正在尝试将带有预先训练的机器学习模型(作为
model.pkl
文件存储在同一目录中)的 Flask 应用程序部署到 Google Cloud Run。容器在本地运行得很好,但在部署到 Cloud Run 时失败,并出现以下错误:
ERROR: (gcloud.run.deploy) Revision 'mymodel-service-00015-svm' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable.
我正在使用的命令:
构建 Docker 镜像:
docker build --no-cache -t gcr.io/dehaproject2024/mymodel:latest .
推送 Docker 镜像:
docker push gcr.io/dehaproject2024/mymodel:latest
部署到 Google Cloud Run:
gcloud run deploy mymodel-service \ --image gcr.io/dehaproject2024/mymodel:latest \ --platform managed \ --region me-west1 \ --allow-unauthenticated
.
├── server.py # The Flask app file
├── Dockerfile # The Dockerfile for building the container
├── model.pkl # The ML model (pickle file)
├── requirements.txt # Dependencies
server.py
(Flask 应用程序):from flask import Flask, request, jsonify
import pandas as pd
import pickle
import os
app = Flask(__name__)
# Load your trained model (assuming it's a pickle file)
model = pickle.load(open('model.pkl', 'rb'))
@app.route('/predict', methods=['POST'])
def predict():
try:
json_data = request.get_json() # Get data posted as JSON
data = pd.DataFrame(json_data) # Convert JSON to pandas DataFrame
# Assuming your model expects the data in the same format as your training data
# Make sure to handle preprocessing if needed
predictions = model.predict(data)
return jsonify(predictions.tolist()) # Return predictions as JSON
except Exception as e:
return jsonify({"error": str(e)}), 400
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8080))
app.run(host="0.0.0.0", port=port)
Dockerfile
:FROM python:3.10-slim
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8080
ENV PORT 8080
CMD ["gunicorn", "--bind", "0.0.0.0:$PORT", "server:app"]
当我像这样运行它时,容器在本地工作:
docker run -p 8080:8080 gcr.io/dehaproject2024/mymodel:latest
我已确认该应用程序在本地运行良好并响应
/predict
端点。
我尝试使用
$PORT
文件和 Dockerfile 中的 server.py
环境变量来确保应用程序绑定到正确的端口。
我仍然收到与上述相同的错误消息。
requirements.txt 是最新的,具有所有必要的依赖项。
EXPOSE 8080
和 ENV PORT 8080
(您要删除后者,因为 云运行文档 说特别是,PORT 环境变量由 Cloud Run 注入容器内。你不应该自己设置
CMD exec gunicorn --bind :$PORT server:app