Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save xyzkpz/bff94653e8842f97435219afb8eff75a to your computer and use it in GitHub Desktop.

Select an option

Save xyzkpz/bff94653e8842f97435219afb8eff75a to your computer and use it in GitHub Desktop.
Creating a Containerized Application with Buildpacks
lab link : - https://www.skills.google/paths/19/course_templates/530/labs/617946
In this lab, you:
Build an application with pack, a command-line tool that is used with builders to create container images from source code.
Use the Google Cloud's buildpacks builder to build a container image.
Run and test the container locally with Docker.
Build and redeploy the container to Cloud Run.
PROJECT_ID=$(gcloud config get-value project)
REGION=us-central1
gcloud config set compute/region $REGION
gcloud services enable artifactregistry.googleapis.com run.googleapis.com translate.googleapis.com
mkdir app && cd app
gcloud storage cp gs://cloud-training/CBL513/sample-apps/sample-py-app.zip . && unzip sample-py-app
cat sample-py-app/main.py
cd sample-py-app
(curl -sSL "https://github.com/buildpacks/pack/releases/download/v0.39.0/pack-v0.39.0-linux.tgz" | sudo tar -C /usr/local/bin/ --no-same-owner -xzv pack)
pack build --builder=gcr.io/buildpacks/builder sample-py-app
docker images
docker run -it -e PORT=8080 -p 8080:8080 -d sample-py-app
curl http://localhost:8080/
main.py
from flask import Flask, request
import google.auth
from google.cloud import translate
app = Flask(__name__)
_, PROJECT_ID = google.auth.default()
TRANSLATE = translate.TranslationServiceClient()
PARENT = 'projects/{}'.format(PROJECT_ID)
SOURCE, TARGET = ('en', 'English'), ('es', 'Spanish')
@app.route('/', methods=['GET', 'POST'])
def index():
# reset all variables
text = translated = None
if request.method == 'POST':
text = request.get_json().get('text').strip()
if text:
data = {
'contents': [text],
'parent': PARENT,
'target_language_code': TARGET[0],
}
# handle older call for backwards-compatibility
try:
rsp = TRANSLATE.translate_text(request=data)
except TypeError:
rsp = TRANSLATE.translate_text(**data)
translated = rsp.translations[0].translated_text
# create context
context = {
'trtext': translated
}
return context
if __name__ == "__main__":
# Dev only: run "python main.py" and open http://localhost:8080
import os
app.run(host="localhost", port=int(os.environ.get('PORT', 8080)), debug=True)
gcloud run deploy sample-py-app --source . --region=${REGION} --allow-unauthenticated
SERVICE_URL=$(gcloud run services describe sample-py-app --region=${REGION} --format="value(status.url)"); echo $SERVICE_URL
curl $SERVICE_URL -H 'Content-Type: application/json' -d '{"text" : "Welcome to this sample app, built with Google Cloud buildpacks."}'
https://github.com/buildpacks/pack/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment