Running GCP Cloud Run from scratch with POST call using superfast steps
Google Console has a plethora of offerings. One such offering is called Cloud Run. Cloud Run is GCP’s container-based serverless compute service that executes code in response to events based on triggers. Cloud Run is a service for running containers in google cloud or Kubernetes clusters. Its primarily designed for stateless containers. Here stateless means if a container starts & fails than the 2nd container will not depend on the first.
Cloud Run is invocable via HTTPs. Users can opt as a managed service or Anthos. Anthos is an application management platform based on Kubernetes. The biggest advantage of using Anthos it spans across clouds and on-prem thereby making cloud run truly portable.
You can find more details on Cloud Run here: https://cloud.google.com/run
In this blog, we will focus on a fast tutorial on setting up & deploying Cloud Run for a POST request call and JSON data request. Let's get started:
At this point, I am assuming you have already done a project setup in GCP and also have access to Cloud Run API and is able to access GCP using gcloud from your local matching. If not, I suggest following this tutorial: https://codelabs.developers.google.com/codelabs/cloud-shell/index.html#0
Steps to build a GCP Cloud Run application:
- Create and goto a local directory using the below command:
mkdir ~/helloworld
cd ~/helloworld
2. Create a file main.py (using vim\nano\any other methods you prefer) and add the below content to the file:
from flask import Flask, request
app = Flask(__name__)@app.route('/jsonexample', methods=['POST'])
def jsonexample():
req_data = request.get_json()
name = req_data['name']
return f'Hello {}!'.format(name)
In the above segment of code, we are creating the POST method and read the input JSON data using request.
3. Now your code is ready, you will need to dockerize (for dependencies) the same using a Dockerfile. So, create a Dockerfile in the same folder and paste the below code:
# Use the official lightweight Python image.
# https://hub.docker.com/_/pythonFROM python:3.8-slim# Allow statements and log messages to immediately appear in the Knative logsENV PYTHONUNBUFFERED True# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./# Install production dependencies.
RUN pip install Flask gunicorn# 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.CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app
4. Just for safety, include a .dockerignore file as well and paste the below code:
Dockerfile
README.md
*.pyc
*.pyo
*.pyd
__pycache__
.pytest_cache
5. Now all the coding is done, feel free to edit main.py and Dockerfile as per your need. The next step to this is to submit the docker image to google gcr for the registry. Replace <PROJECT> by your project. This can be done using the below line:
gcloud builds submit — tag gcr.io/<PROJECT>/helloworld
6. Finally, deploy your code using the below command:
gcloud run deploy --image gcr.io/<PROJECT>/helloworld --platform managed
Once you run the above command, you will be asked to give a “Service Name”, “Region” and “Allow unauthenticated invocations” — select ‘y’ for this, select as per your needs.
That's it!! You have successfully deployed Cloud Run.
What happens when you deploy using Cloud Run?
On deployment, Cloud Run expose a HTTP which looks something like this — https://hellowworldv2-456ptldbba-as.a.run.app
In the above URL, you would need to add the route (as shown in main.py), so your accessible URL becomes:
https://hellowworldv2-456ptldbba-as.a.run.app/jsonexample
How to test this?
Below python code can be used to send a JSON data and URL generated:
import json
import requestsresponse = requests.post('https://hellowworldv2-456ptldbba-as.a.run.app/jsonexample', json={"name" : "Python"})print(response.text)
About the Author,
LinkedIn: https://www.linkedin.com/in/subarna-rana/
Thank you
References:
https://codelabs.developers.google.com/codelabs/cloud-run-hello-python3/#3