How to Deploy a Cloud Function on Google Cloud Platform
To deploy a cloud function on Google Cloud Platform, use the
gcloud functions deploy command with your function name, runtime, trigger, and source code location. This command packages your code and sets up the function to run in the cloud.Syntax
The basic command to deploy a Google Cloud Function is:
- gcloud functions deploy FUNCTION_NAME: Names your function.
- --runtime RUNTIME: Specifies the language runtime (like nodejs18, python39).
- --trigger-http: Sets the function to run on HTTP requests.
- --entry-point ENTRY_POINT: (Optional) The function name in your code to run.
- --source SOURCE_DIR: (Optional) Path to your function code folder.
bash
gcloud functions deploy FUNCTION_NAME --runtime RUNTIME --trigger-http --entry-point ENTRY_POINT --source SOURCE_DIR
Example
This example deploys a simple HTTP function named helloWorld written in Node.js 18. The function responds with 'Hello, World!' when called.
javascript
exports.helloWorld = (req, res) => {
res.send('Hello, World!');
};Example Deployment Command
Run this command in your terminal inside the folder containing the index.js file with the function code:
bash
gcloud functions deploy helloWorld --runtime nodejs18 --trigger-http --allow-unauthenticated
Output
Deploying function (may take a while)...
Deployments successful
availableMemoryMb: 256
entryPoint: helloWorld
httpsTrigger:
url: https://REGION-PROJECT_ID.cloudfunctions.net/helloWorld
runtime: nodejs18
serviceAccountEmail: PROJECT_ID@appspot.gserviceaccount.com
status: ACTIVE
timeout: 60s
versionId: 1
Common Pitfalls
- Forgetting to specify
--trigger-httpwhen you want an HTTP function causes deployment errors. - Not setting
--allow-unauthenticatedmeans your function requires authentication and may not respond publicly. - Using the wrong runtime version causes deployment failure; check supported runtimes with
gcloud functions runtimes list. - Not running the command in the correct source folder or missing
--sourceleads to missing code errors.
bash
Wrong: gcloud functions deploy myFunc --runtime python39 Right: gcloud functions deploy myFunc --runtime python39 --trigger-http --allow-unauthenticated
Quick Reference
| Option | Description |
|---|---|
| FUNCTION_NAME | Name of your cloud function |
| --runtime | Language runtime (e.g., nodejs18, python39) |
| --trigger-http | Trigger function via HTTP requests |
| --entry-point | Function name in your code (default is 'function') |
| --source | Path to your function code folder |
| --allow-unauthenticated | Allow public access without login |
Key Takeaways
Use the gcloud CLI with 'gcloud functions deploy' to deploy your cloud function.
Specify the runtime and trigger type clearly to avoid deployment errors.
Include '--allow-unauthenticated' for public HTTP functions.
Keep your function code in the right folder or specify it with '--source'.
Check supported runtimes with 'gcloud functions runtimes list' before deploying.