Dev tips when making a Cloud Run service

  1. You can identify if your service is running on a Knative platform like Cloud Run by looking for the K_SERVICE environment variable.
    https://docs.cloud.google.com/run/docs/container-contract#env-vars
  2. When connecting to Cloud SQL, you should switch to IAM authentication and only use a connection string as a local fallback. Set a CLOUD_SQL_INSTANCE variable only in the deploy environment, and your application can detect this and use @google-cloud/cloud-sql-connector.
    https://docs.cloud.google.com/sql/docs/mysql/connect-connectors#node.js
  3. Correlate your container logs with a request log (services only)
    By default, container logs are not correlated with request logs. To link them without a client library like @google-cloud/logging, write a structured JSON log containing a logging.googleapis.com/trace field with the trace identifier extracted from the X-Cloud-Trace-Context request header.
    https://docs.cloud.google.com/run/docs/logging#writing_structured_logs
  4. Remember that Cloud Run is a serverless service, meaning instances can be scaled down at any time. If required, install a SIGTERM handler in your application to receive a warning when Cloud Run is about to shut down an instance. You will have a 10-second window to react.
    https://docs.cloud.google.com/run/docs/container-contract#instance-shutdown
  5. Cloud Run uses an in-memory file system, so every file you write to the instance is actually consuming your instance’s memory.
  6. Outbound network connections from Cloud Run can occasionally be terminated, either due to timeout or infrastructure restarts. If your application reuses long-lived connections, we recommend configuring it to re-establish connections to avoid reusing a dead connection.
  7. Cloud Run injects a PORT environment variable and expects your application to listen on it. Do not hardcode a port number (e.g. 8080); always read from process.env.PORT instead.