0
0
GcpHow-ToBeginner · 3 min read

How to Set Memory and CPU in Cloud Run

To set memory and CPU in Cloud Run, use the --memory and --cpu flags with the gcloud run deploy command or specify them in the service's YAML configuration under resources.limits. This controls how much memory and CPU your container gets when running.
📐

Syntax

Use the gcloud run deploy command with these flags:

  • --memory: Sets the amount of memory allocated (e.g., 512Mi, 1Gi).
  • --cpu: Sets the number of CPU cores (e.g., 1, 2).

Alternatively, in the YAML file, specify under resources.limits:

resources:
  limits:
    memory: 512Mi
    cpu: 1
bash
gcloud run deploy SERVICE_NAME --image IMAGE_URL --memory MEMORY --cpu CPU
💻

Example

This example deploys a Cloud Run service named my-service with 1 GiB memory and 2 CPUs.

bash
gcloud run deploy my-service \
  --image gcr.io/my-project/my-image \
  --memory 1Gi \
  --cpu 2 \
  --region us-central1 \
  --platform managed
Output
Deploying service [my-service]... Done. Service [my-service] revision [my-service-00001-abc] has been deployed and is serving 100 percent of traffic.
⚠️

Common Pitfalls

Common mistakes when setting memory and CPU in Cloud Run include:

  • Using unsupported memory units or CPU values (must be valid like 512Mi, 1Gi, or integer CPUs).
  • Not specifying both --memory and --cpu when needed, leading to default resource allocation.
  • Setting CPU higher than memory allows, which can cause deployment errors.
  • Forgetting to redeploy the service after changing resource settings.
bash
gcloud run deploy my-service --image gcr.io/my-project/my-image --memory 1000 --cpu 1
# Wrong: '1000' is not a valid memory unit

gcloud run deploy my-service --image gcr.io/my-project/my-image --memory 1Gi --cpu 0.5
# Wrong: CPU must be an integer (e.g., 1, 2)
📊

Quick Reference

Flag/FieldDescriptionExample Values
--memoryAmount of memory allocated to the container256Mi, 512Mi, 1Gi, 2Gi
--cpuNumber of CPU cores allocated1, 2, 4
resources.limits.memoryMemory limit in YAML config512Mi, 1Gi
resources.limits.cpuCPU limit in YAML config1, 2

Key Takeaways

Use --memory and --cpu flags with gcloud run deploy to set resources.
Memory values must include units like Mi or Gi; CPU must be an integer.
Always redeploy your Cloud Run service after changing resource settings.
Match CPU and memory settings to your workload needs to optimize cost and performance.