Encountering a 503 error after deploying Flask on CloudRun

I encountered an issue while trying to deploy a simple Flask app that utilizes Google Bucket. Upon deployment, I kept getting error 503 - Service Unavailable.

I'm unsure if I missed something crucial or what exactly I might be doing wrong. Any assistance or guidance would be greatly appreciated...

import os
import json
from flask import Flask, render_template, request, jsonify
from google.cloud import storage

app = Flask(__name__)

storage_client = storage.Client.from_service_account_json('/home/hajnyondra/hello-world-1/test22-401315-883f659ea7a6.json')

bucket_name = 'json_uloziste'
BUCKET = storage_client.get_bucket(bucket_name)

received_values = []
pocitac = 0

def create_json(json_object, filename):
    blob = BUCKET.blob(filename)
    blob.upload_from_string(
        data=json.dumps(json_object),
        content_type='application/json'
    )
    result = filename + ' upload complete'
    return {'response': result}

def get_json(filename):
    blob = BUCKET.get_blob(filename)
    file_data = json.loads(blob.download_as_string())
    return file_data

@app.route('/')
def hello():
    return render_template('index.html')

@app.route('/p', methods=['POST'])
def lol():
    global pocitac, received_values
    received_data = request.form['data']
    print(f'Received data: {received_data}')

    if received_data == '777': 
        pocitac = pocitac + 1
        json_data = json.dumps(received_values)
        create_json(json_data, "RUN" + str(pocitac))
        received_values = []
    
    else:
        received_values.append(float(received_data))

    return "nazdar"

@app.route('/data', methods=['GET'])
def get_data():
    return jsonify(received_values)

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

Dockerfile:


# Use the official lightweight Python image.
# https://hub.docker.com/_/python
FROM python:3.11-slim

# Allow statements and log messages to immediately appear in the logs
ENV PYTHONUNBUFFERED True

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./

# Install production dependencies.
RUN pip install --no-cache-dir -r requirements.txt

# Run the web service on container startup. Here we use the gunicorn
# webserver, with one worker process and 8 threads.
# For environments with multiple CPU cores, increase the number of workers
# to be equal to the cores available.
# Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling.
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

Requirements:

Flask
requests
gunicorn
google-cloud-storage
debugpy # Required for debugging.

I attempted to adjust versions and Docker configurations, but it resulted in either failed deployments or requests returning 503 errors consistently...

Answer №1

Unfortunately, the code is not functioning as expected.

In short: the issue arises from attempting to load a service account key file from a non-existent location.

storage_client = storage.Client.from_service_account_json('/home/hajnyondra/hello-world-1/test22-401315-883f659ea7a6.json')

The directory /home does not exist; consider placing your application in /app within your container instead.

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME

This problem presents an opportunity for improvement, particularly in terms of security measures.

  • (Poor Practice) Failing to utilize a service account key file (except under rare circumstances).
  • (Unfavorable pattern) Hard-coding sensitive paths within the codebase.

It is advisable to adopt ADC (Application Default Credential) as an alternative approach. By doing so, the credential location is not explicitly specified; rather, the Google Cloud client library can detect it autonomously based on the runtime environment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to repeatedly test the payload by simulating a POST request using pytest?

I have a function that sends data to an external API using the `requests.post()` method. I need to test whether the data meets specific criteria during testing by mocking the requests module and capturing the payload. Ideally, I prefer not to introduce ext ...

What is the most effective way to extract all distinct HTML tags from a webpage using regular expressions?

On a recent HTML page, I managed to extract the following source code: import requests text = requests.get("https://en.wikipedia.org/wiki/Collatz_conjecture").text My goal now is to determine the count of unique HTML tags present on this webpag ...

What is the best way to store 100 binary images in one file?

Is there a Python library that can handle saving 100 binary images of type .bmp into a single file, and then later reading each image from that file individually? If such a library does not exist, my alternative plan is to read all 100 binary images, stor ...

List of numbers combined in a one-of-a-kind sequence

From a generated list of numbers, I aim to create new numbers by combining them. Here is the initial list: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] I expect the new list to be as follows: [23, 25, 27, 211, 213, 217, 219, 223, 229, 231, 32, 35, 37, 3 ...

Is there a way to execute a bash script from a python program while maintaining the same input and output?

I am currently working on executing a program from a Python script in the shell. I have come across some solutions such as: def bash(cmd): subprocess.Popen(cmd, shell=True, executable='/bin/bash') bash('./my/file') However, one pr ...

Is there a more efficient method to reduce processing time when extracting and storing specific numbers from a large file into multiple other large files?

Seeking efficiency in handling large file comparison process I am working on a code that involves reading a massive file (200,000 kB), where the goal is to compare two lines at a time and extract the difference between numbers from line n and line n-1 int ...

404 error: Docker container hosting static ReactJS files unable to locate page

I have been attempting to containerize a Go application that serves static files on port 8000. Despite trying suggestions from other sources, such as using router.Run("0.0.0.0:8000") or router.Run(":8000"), I have not been successful. H ...

I'm having trouble retrieving the episode ids using imdbpy

I am new to Python and currently working on fetching movie information using Imdbpy. The code snippet I have written is as follows: ia = IMDb() results = ia.search_movie(movie_name) movie_id = results[0].getID() movie = ia.get_movie(movie_id) If the movie ...

The mod_wsgi module encountered a TypeError due to an unexpected data type, specifically a byte string object was expected for the header name

Currently, I have a Flask web application running in Production with Python 2.7.5 and mod_wsgi 3.4. The webapp is working perfectly both in production and on local loopback. Recently, I incorporated a Flask Restplus API consisting of three methods. Locall ...

Slowly scrolling down using Selenium

Struggling with performing dynamic web scraping on a javascript-rendered webpage using Python. 1) Encountering an issue where elements load only when scrolling down the page slowly. Tried methods such as: driver.execute_script("window.scrollTo(0, Y)") ...

Searching for a div table using XPATH in Python

Struggling to extract data from a table using Selenium in Python. Any suggestions on how to achieve this? https://i.stack.imgur.com/rPlKR.png <div class="js--property-table-body project-property-table__body"> <span aria-hidden=&quo ...

Bringing in the flask extension for web forms - flask.ext.w

Currently, I am utilizing venv and developing with Eclipse. My objective is to integrate a contact page into my project. This is what I have done so far: $ . bin/activate $ pip install flask-wtf In my forms.py file, I have imported some modules: I init ...

Identify a duplicate class name element using Selenium

<ul class="k9GMp "> <li class="Y8-fY "><span class="-nal3 "><span class="g47SY ">2</span> posts</span> </li> <li class="Y8-fY "><a class="-nal3 " href="/username/followers/" tabindex="0"><span ...

encountering problems when installing Jupyter with pip on Python version 2.7.3

Our organization is utilizing Python 2.7.3 and unfortunately, Anaconda is not available in the approved package list. This has led us to manually installing dependencies using unofficial Windows binaries provided by Christoph Gohlke. However, we are curren ...

Building libtorrent Rasterbar on Mavericks

Boost was successfully compiled and installed from source with the following commands: $pwd /Downloads/boost_1_58_0 ./b2 threading=multi link=static runtime-link=static cxxflags="-stdlib=libstdc++" linkflags="-stdlib=libstdc++" Upon completion of the b ...

When using the Pandas `read_csv` function, be aware that there may be hidden characters embedded within

Trying to access a CSV file provided through this link, which is commonly used for building recommendation systems. Specifically, using BX-Books.csv and BX-Book-Ratings.csv. Here's an excerpt from the BX-Books.csv: "ISBN";"Book-Title&qu ...

Can Python be used to determine if an object is connected to the audio jack?

Looking to identify if there is a device connected to the audio jack using python. Specifically on Windows 7. ...

Python code to calculate the first 1000 digits of pi

I've been grappling with this problem for some time now and I just can't seem to crack it. Maybe you could lend me a hand. The issue is that my Python code isn't producing the 1000 digits of pi like it's supposed to. Here's the sn ...

Troubleshooting Python Bottle's Failure to Return an Item

Whenever utilizing: from bottle import route, run, request, view N = 0 def produceitem(): global N for i in range(100): N = i yield i @route('/') @view('index.html') def home(): print produceitem() pr ...

Scraping images with BeautifulSoup4 and Selenium

I am currently working on scraping image files from Instagram using selenium and bs4. The script I have works well, but my goal is to only print out the img src link for now, like this: https://scontent-lax3-2.cdninstagram.com/vp/2592f6b07f88bfc4bfdf6d7340 ...