-
-
Notifications
You must be signed in to change notification settings - Fork 605
Cloud Run Deployment
This tutorial demonstrates how to deploy a NiceGUI application on Cloud Run
Create a Python file main.py
with the following content:
from random import choice
from nicegui import ui
greetings = [
"Hello!",
"Hi there!",
"Good morning!",
"Good afternoon!",
"Hey!",
"Greetings!",
"Howdy!",
"Nice to see you!",
"Lovely day, isn't it?",
"Welcome!"
]
ui.button('Greet', on_click=lambda: ui.notify(choice(greetings)))
ui.run(reload=False, port=8080)
Create a Dockerfile
which describes the setup of your app:
FROM zauberzeug/nicegui:1.4.22
COPY main.py /app
CMD ["python", "main.py"]
Install and setup the gcloud CLI and activate all the services related to Cloud Run, Cloud Build and Artifacts Registry in your GCP project.
Run the following script:
# Fetch the current project ID from gcloud configuration
PROJECT_ID=$(gcloud config get-value project)
# Define variables
REPO="demo"
LOCATION="europe-west1"
IMAGE="demo-app"
VERSION="0.0.1"
# Construct the container image tag
GAR_TAG=$LOCATION-docker.pkg.dev/$PROJECT_ID/$REPO/$IMAGE:$VERSION
# Create repository
# If it fails because it already exists, it's fine
gcloud artifacts repositories create $REPO --repository-format=docker \
--location=$LOCATION --description="Docker repository" \
--project=$PROJECT_ID || true
# Build image
gcloud builds submit --tag $GAR_TAG
# Deploy Cloud Run service
gcloud run deploy $IMAGE --image=$GAR_TAG --max-instances=1 --min-instances=0 --port=8080 \
--allow-unauthenticated --region=europe-west1 --memory=1Gi --cpu=1 -q --no-cpu-throttling --session-affinity \
--concurrency 300 --timeout 1800
You can of course adjust the parameters of the deployment to suit your use case but make sure to keep the following two options:
-
--no-cpu-throttling: This flag is used to disable CPU throttling for Cloud Run services. This helps avoid having the page constantly refresh because the CPU was shut down between requests on the backend.
-
--session-affinity: This flag enables session affinity for incoming requests to the Cloud Run service. Session affinity ensures that requests from the same client are routed to the same instance of the service during the lifetime of the session.
Your app is ready to access on https://demo-app-RANDOM-ew.a.run.app, RANDOM will be replaced with a random sub-string.