Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
HTTP-Cloud Run Functions-Funktion mit Ruby (1. Generation) erstellen und bereitstellen
Dieser Leitfaden erläutert den Prozess zum Schreiben einer Cloud Run Functions-Funktion mithilfe der Ruby-Laufzeit. Es gibt zwei Arten von Cloud Run-Funktionen:
Eine HTTP-Funktion, die Sie über Standard-HTTP-Anfragen aufrufen.
Eine durch ein Ereignis ausgelöste Funktion, mit der Sie Ereignisse aus Ihrer Cloud-Infrastruktur verarbeiten können, z. B. Nachrichten in einem Pub/Sub-Thema oder Änderungen in einem Cloud Storage-Bucket.
Das Beispiel zeigt, wie Sie eine einfache HTTP-Funktion erstellen.
Hinweise
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Erstellen Sie eine app.rb-Datei im Verzeichnis helloworld mit folgendem Inhalt:
require"functions_framework"require"cgi"require"json"FunctionsFramework.http"hello_http"do|request|# The request parameter is a Rack::Request object.# See https://www.rubydoc.info/gems/rack/Rack/Requestname=request.params["name"]||(request.body.rewind && JSON.parse(request.body.read)["name"]rescuenil)||"World"# Return the response body as a string.# You can also return a Rack::Response object, a Rack response array, or# a hash which will be JSON-encoded into a response."Hello #{CGI.escape_htmlname}!"end
Diese Beispielfunktion verwendet einen in der HTTP-Anfrage angegebenen Namen und gibt eine Begrüßung bzw. „Hello World!“, wenn kein Name angegeben wird, zurück.
Abhängigkeiten angeben
Abhängigkeiten in Ruby werden mit Bundler verwaltet und in einer Datei namens Gemfile ausgedrückt.
Wenn Sie die Funktion bereitstellen, lädt Cloud Run Functions die in Gemfile und Gemfile.lock deklarierten Abhängigkeiten mithilfe von bundler herunter und installiert sie.
Unter Gemfile sind die für Ihre Funktion erforderlichen Pakete sowie optionale Versionseinschränkungen aufgelistet. Bei einer Cloud Run Functions-Funktion muss eines dieser Pakete das Gem functions_framework sein.
Erstellen Sie für diese Übung eine Datei mit dem Namen Gemfile im selben Verzeichnis wie die Datei app.rb, die den Funktionscode enthält:
Führen Sie den folgenden Befehl aus, um das Gem functions_framework und andere Abhängigkeiten zu installieren:
bundleinstall
Build lokal erstellen und testen
Bevor Sie die Funktion bereitstellen, können Sie sie lokal erstellen und testen:
Führen Sie den folgenden Befehl aus, um die ausführbare Datei functions-framework-ruby zu verwenden, um einen lokalen Webserver zu starten, auf dem die hello_http-Funktion ausgeführt wird:
bundleexecfunctions-framework-ruby--targethello_http# ...starts the web server in the foreground
Wenn die Funktion erfolgreich erstellt wird, wird die URL angezeigt, die Sie in Ihrem Webbrowser aufrufen können, um die Funktion in Aktion zu sehen: http://localhost:8080/. Die Meldung Hello World! sollte angezeigt werden.
Alternativ können Sie Anfragen mit curl von einem anderen Terminalfenster aus an diese Funktion senden:
curllocalhost:8080# Output: Hello World!
Siehe auch Funktionen testen in der Dokumentation zu Ruby Functions Framework.
Funktion implementieren
Stellen Sie die Funktion mit einem HTTP-Trigger mit diesem Befehl im Verzeichnis helloworld bereit:
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 2025-08-25 (UTC)."],[[["\u003cp\u003eThis guide details how to create and deploy an HTTP Cloud Run function using the Ruby runtime environment, enabling it to be invoked via standard HTTP requests.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves creating an \u003ccode\u003eapp.rb\u003c/code\u003e file with the function code, which, in this example, generates a personalized greeting based on a name provided in the HTTP request, defaulting to "Hello World!".\u003c/p\u003e\n"],["\u003cp\u003eDependencies for the Ruby Cloud Run function are managed using Bundler and a \u003ccode\u003eGemfile\u003c/code\u003e, where \u003ccode\u003efunctions_framework\u003c/code\u003e gem is required, and they are installed during the deployment.\u003c/p\u003e\n"],["\u003cp\u003eBefore deploying, the function can be built and tested locally using \u003ccode\u003efunctions-framework-ruby\u003c/code\u003e, allowing verification of its behavior before it goes live.\u003c/p\u003e\n"],["\u003cp\u003eThe function is deployed via the \u003ccode\u003egcloud functions deploy\u003c/code\u003e command, which can include the \u003ccode\u003e--allow-unauthenticated\u003c/code\u003e flag to permit access without requiring prior authentication.\u003c/p\u003e\n"]]],[],null,["# Quickstart: Create and deploy an HTTP Cloud Run function by using Ruby\n\nCreate and deploy an HTTP Cloud Run function by using Ruby (1st gen)\n====================================================================\n\nThis guide takes you through the process of writing a Cloud Run function\nusing the Ruby runtime. There are two types of Cloud Run functions:\n\n- An HTTP function, which you invoke from standard HTTP requests.\n- An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Pub/Sub topic, or changes in a Cloud Storage bucket.\n\nThe sample shows how to create a simple HTTP function.\n| **Learn more** : For more details, read about [HTTP functions](/functions/1stgendocs/writing/write-http-functions) and [event-driven functions](/functions/1stgendocs/writing/write-event-driven-functions).\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/quickstart)\n\n1. [Install and initialize the gcloud CLI](/sdk/docs).\n2. Update and install `gcloud` components: \n\n ```bash\n gcloud components update\n ```\n| **Note** : Need a command prompt? You can use [Cloud Shell](https://console.cloud.google.com/?cloudshell=true). Cloud Shell is a command line environment that already includes the Google Cloud CLI, so you don't need to install it. The Google Cloud CLI also comes preinstalled on Compute Engine Virtual Machines.\n3. Prepare your development environment.\n [Go to the Ruby setup guide](/ruby/docs/setup)\n\nCreate a function\n-----------------\n\n1. Create a directory on your local system for the function code:\n\n ### Linux or Mac OS X\n\n mkdir ~/helloworld\n cd ~/helloworld\n\n ### Windows\n\n mkdir %HOMEPATH%\\helloworld\n cd %HOMEPATH%\\helloworld\n\n2. Create an `app.rb` file in the `helloworld` directory with the\n following contents:\n\n require \"functions_framework\"\n require \"cgi\"\n require \"json\"\n\n FunctionsFramework.http \"hello_http\" do |request|\n # The request parameter is a Rack::Request object.\n # See https://www.rubydoc.info/gems/rack/Rack/Request\n name = request.params[\"name\"] ||\n (request.body.rewind && JSON.parse(request.body.read)[\"name\"] rescue nil) ||\n \"World\"\n # Return the response body as a string.\n # You can also return a Rack::Response object, a Rack response array, or\n # a hash which will be JSON-encoded into a response.\n \"Hello #{CGI.escape_html name}!\"\n end\n\n This example function takes a name supplied in the HTTP request and returns\n a greeting, or \"Hello World!\" when no name is supplied.\n | **Note:** Cloud Run functions looks for deployable functions in `app.rb` by default. Use the [`--source`](/sdk/gcloud/reference/functions/deploy#--source) flag when [deploying your function using `gcloud`](#deploy_the_function) to specify a different directory containing an `app.rb` file.\n\nSpecify dependencies\n--------------------\n\nDependencies in Ruby are managed with [bundler](https://bundler.io) and expressed in a file called\n`Gemfile`.\n\nWhen you deploy your function, Cloud Run functions downloads and installs the\ndependencies declared in the `Gemfile` and `Gemfile.lock` using `bundler`.\n\nThe `Gemfile` lists the packages required by your function, along with any\noptional version constraints. For a Cloud Run function, one of these\npackages must be the `functions_framework` gem.\n\nFor this exercise, create a file named `Gemfile` in the same directory as the\n`app.rb` file that contains your function code, with the following contents: \n\n```\nsource \"https://rubygems.org\"\n\ngem \"functions_framework\", \"~\u003e 0.7\"\n```\n\nRun the following command to install the `functions_framework` gem and other\ndependencies: \n\n bundle install\n\n| **Learn more** : For more details, read about [specifying dependencies](/functions/1stgendocs/writing/specifying-dependencies-ruby).\n\nBuild and test locally\n----------------------\n\nBefore deploying the function, you can build and test it locally.\nRun the following command to use the `functions-framework-ruby` executable to\nstart a local web server running your `hello_http` function: \n\n bundle exec functions-framework-ruby --target hello_http\n # ...starts the web server in the foreground\n\nIf the function builds successfully, it displays the URL you can visit in your\nweb browser to see the function in action:\n`http://localhost:8080/`. You should see a `Hello World!` message.\n\nAlternatively, you can send requests to this function using `curl` from another\nterminal window: \n\n curl localhost:8080\n # Output: Hello World!\n\nSee [Testing Functions](https://github.com/GoogleCloudPlatform/functions-framework-ruby#documentation)\nin the Ruby Functions Framework documentation.\n\nDeploy the function\n-------------------\n\nTo deploy the function with an HTTP trigger, run the following\ncommand in the `helloworld` directory: \n\n gcloud functions deploy hello_http --no-gen2 --runtime ruby33 --trigger-http --allow-unauthenticated\n\nThe `--allow-unauthenticated` flag lets you reach the function\n[without authentication](/functions/1stgendocs/securing/managing-access-iam#allowing_unauthenticated_http_function_invocation).\nTo require\n[authentication](/functions/1stgendocs/securing/authenticating#developers), omit the\nflag.\n| **Learn more** : For more details, read about [deploying Cloud Run functions](/functions/1stgendocs/deploy#basics).\n\nTest the deployed function\n--------------------------\n\n1. When the function finishes deploying, take note of the `httpsTrigger.url`\n property or find it using the following command:\n\n gcloud functions describe hello_http\n\n It should look like this: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http\n ```\n2. Visit this URL in your browser. You should see a \"Hello World!\" message.\n\n Try passing a name in the HTTP request, for example by using the following\n URL: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/hello_http?name=NAME\n ```\n\n You should see the message \"Hello \u003cvar translate=\"no\"\u003eNAME\u003c/var\u003e!\"\n\nView logs\n---------\n\nYou can view Cloud Run functions logs in the Cloud Logging UI or through the\nGoogle Cloud CLI.\n\n### View logs with the command-line tool\n\nTo view logs for your function with the gcloud CLI, use the\n[`logs read`](/sdk/gcloud/reference/functions/logs/read) command, followed by\nthe name of the function: \n\n```bash\ngcloud functions logs read hello_http\n```\n\nThe output should resemble the following: \n\n```bash\nLEVEL NAME EXECUTION_ID TIME_UTC LOG\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:25.983 Function execution started\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:26.001 Function execution took 19 ms, finished with status code: 200\n```\n| **Note:** There is typically a slight delay between when log entries are created and when they show up in Cloud Logging.\n\n### View logs in the Logging dashboard\n\nYou can also view logs for Cloud Run functions from the\n[Google Cloud console](https://console.cloud.google.com/project/_/logs?service=cloudfunctions.googleapis.com).\n| **Learn more** : For more details, read about [writing, viewing, and responding to logs](/functions/1stgendocs/monitoring/logging)."]]