ОШИБКА: (gcloud.app.deploy) Ошибка: [9] Ошибка запуска приложения: - PullRequest
0 голосов
/ 30 июня 2018

Когда я запускаю gcloud app deploy, я получаю ответ об ошибке 9. Я получаю сообщение об ошибке

Updating service [default] (this may take several minutes)...failed.                                                                                                                
ERROR: (gcloud.app.deploy) Error Response: [9] 
Application startup error:

app.js

// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore');

// Your Google Cloud Platform project ID
const projectId = 'myid';

// Creates a client
const datastore = new Datastore({
    projectId: projectId,
});

// The kind for the new entity
const kind = 'Task';
// The name/ID for the new entity
const name = 'sampletask1';
// The Cloud Datastore key for the new entity
const taskKey = datastore.key([kind, name]);

// Prepares the new entity
const task = {
    key: taskKey,
    data: {
        description: 'Buy milk',
    },
};

// Saves the entity
datastore
    .save(task)
    .then(() => {
        console.log(`Saved ${task.key.name}: ${task.data.description}`);
    })
    .catch(err => {
        console.error('ERROR:', err);
    });

package.json

{
  "name": "first-application",
  "version": "1.0.0",
  "description": "First program using cloud datastore",
  "main": "app.js",
  "scripts": {
    "start":"node app.js",
    "deploy":"gcloud app deploy",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Ragav",
  "license": "ISC",
  "dependencies": {
    "@google-cloud/datastore": "^1.4.1"
  }
}

app.yaml

runtime: nodejs
vm: true

Пожалуйста, помогите мне, я пытаюсь научиться развертывать сервер приложений на GCP. Ценю вашу помощь.

Спасибо!

1 Ответ

0 голосов
/ 06 июля 2018

Чтобы запустить показанный вами пример, следуйте инструкциям в документации :

  1. Загрузите файл учетных данных JSON и создайте переменную среды, которая указывает на этот файл:

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/credential-file.json"

  1. Скопируйте код в файл 1011 * и запустите node sample.js.

С другой стороны, если вы хотите развернуть приложение nodejs, вам потребуется express.js или любая другая инфраструктура.

Я сделал следующее с помощью express.js:

Я завернул ваш код в функцию под названием saveEntity(datastore)

Затем я добавил express.js в приложение, как в примере приложения nodejs , и оттуда я вызвал saveEntity (datastore):

app.get('/', (req, res) => {
    saveEntity(datastore);
    res.status(200).send("Entity saved").end();
}); 

// [START listen]
const PORT = process.env.PORT || 8080;
app.listen(process.env.PORT || 8080, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;

Полный результат таков:

// Imports the Google Cloud client library
const Datastore = require('@google-cloud/datastore');
//Needed to create the node app
const express = require('express')

const app = express();

// Your Google Cloud Platform project ID
const projectId = 'my-project-id';

// Creates a client
const datastore = new Datastore({
    projectId: projectId,
});

function saveEntity(datastore){
    // The kind for the new entity
    const kind = 'JulyTask';
    // The name/ID for the new entity
    const name = 'sampletask1';
    // The Cloud Datastore key for the new entity
    const taskKey = datastore.key([kind, name]);

    // Creates entity data
    const task = {
        name: 'Learn something',
        status: 'In progress',
        description: 'Friday 6 July'
    }

    //With the data and the key, create the entity
    const entity = {
        key: taskKey,
        data: task
    }

    // Saves the entity
    datastore
        .upsert(entity)
        .then(() => {
            console.log('Saved:\n' + JSON.stringify(entity));
            return true;
        })
        .catch(err => {
            console.error('ERROR:', err);
            return false;
        });
}

app.get('/', (req, res) => {
    saveEntity(datastore);
    res.status(200).send("Entity saved").end();
}); 

// [START listen]
const PORT = process.env.PORT || 8080;
app.listen(process.env.PORT || 8080, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;

package.json:

{
    "name": "first-application",
    "version": "1.0.0",
    "description": "First program using cloud datastore",
    "main": "app.js",
    "scripts": {
        "start": "node app.js",
        "deploy": "gcloud app deploy",
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "Ragav",
    "license": "ISC",
    "dependencies": {
        "@google-cloud/datastore": "^1.4.1",
        "express": "^4.16.3"
    }
}

Также вы должны знать, что это устарело :

runtime: nodejs
vm: true

Вы могли бы сделать это вместо:

runtime: nodejs
env: flex
service: my-service-name
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...