Flask App Works Locally But Fails to Deploy on Google Cloud Run: “Failed to Start and Listen on the Port”

Problem:

I’m trying to deploy a Flask app with a pre-trained machine learning model (stored as a model.pkl file in the same directory) to Google Cloud Run. The container runs perfectly fine locally, but fails when deploying to Cloud Run with the following error:

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.

Commands I’m Using:

  1. Building the Docker image:

    docker build --no-cache -t gcr.io/dehaproject2024/mymodel:latest .

  2. Pushing the Docker image:

    docker push gcr.io/dehaproject2024/mymodel:latest

  3. Deploying to Google Cloud Run:

    gcloud run deploy mymodel-service --image gcr.io/dehaproject2024/mymodel:latest --platform managed --region me-west1 --allow-unauthenticated

The Project Structure:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>.
├── server.py # The Flask app file
├── Dockerfile # The Dockerfile for building the container
├── model.pkl # The ML model (pickle file)
├── requirements.txt # Dependencies
</code>
<code>. ├── server.py # The Flask app file ├── Dockerfile # The Dockerfile for building the container ├── model.pkl # The ML model (pickle file) ├── requirements.txt # Dependencies </code>
.
├── 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 App):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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"]
</code>
<code>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"] </code>
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"]

What I Tried:

  • The container works locally when I run it like this:

    docker run -p 8080:8080 gcr.io/dehaproject2024/mymodel:latest

  • I have confirmed the app runs fine locally and responds to /predict endpoint.

  • I’ve tried making sure that the app is binding to the correct port by using $PORT environment variable, both in the server.py file and the Dockerfile.

  • I’m still getting the same error message as stated above.

  • the requirements.txt is up-to-date with all necessary dependencies.

What Could Be the Issue?

3

  1. Remove EXPOSE 8080 and ENV PORT 8080(You’re removing the latter because cloud run documentation says

In particular, the PORT environment variable is injected inside your container by Cloud Run. You should not set it yourself

  1. Change the final line to CMD exec gunicorn --bind :$PORT server:app

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật