Search code examples
node.jsgoogle-cloud-platformgoogle-cloud-run

How to create a new service using the Google Cloud Run API for node.js?


I am working on a node.js project on Google Cloud Platform and I want to start new Cloud Run instances whenever a user wants to start a service. Basically, I want to automatically start a visualization server when the user chooses to visualize their results. That is why I decided to use teh GCP Cloud Run API to create new services when needed. However, the API is very poorly documented and I keep receiving the error:

Service has no template

My question is: how do I create a new service using the Google Cloud Run client services API?

I tried using the API and I currently wrote the code in this manner:

// create a new service
async function callCreateService(){
  // construct request
  
  const request = {
  parent,
  template, 
  serviceId,
  };
  
  // Run request
  const [operation] = await runClient.createService(request);
  const [response] = await operation.promise();
  console.log(`The response is ${response}`);
}


console.log('initiated...');

//callListServices();
callCreateService();

I know that the parent is correct because I connected and listed all of the currently running services using the listServices() method, but I can't manage to create a new service using createService() because I don't know the template's structure and Google Cloud Run's API for node.js is very poorly documented.


Solution

  • Yeah you missed the template for creating cloud run service the following are the arguments for it:

    const template = {
      spec: {
        container: {
          image: '<your image path>',
        },
        containerPort: 8080,
      },
      scale: {
        replicas: 1,
      },
    };
    
    const request = {
      parent: 'projects/my-project',
      serviceId: 'my-service',
      template,
    };
    
    const [operation] = await runClient.createService(request);
    const [response] = await operation.promise();
    console.log(`The response is ${response}`);
    

    You can get official documentation for this methods here

    If the above did not work you can also pass template related stuff in service in the above doc it is specified empty but you can fill those within spec object as following:

    const request = {
        parent: 'projects/my-project',
        service: {
          spec: {
            container: {
              image: 'gcr.io/my-project/my-image:latest',
            },
            containerPort: 8080,
          },
          scale: {
            replicas: 1,
          },
        },
        serviceId: '<your_service_id>',
      };