のらねこの気まま暮らし

技術系だけど、Qiita向きではないポエムとかを書くめったに更新されないヤツ

App Engineを試す vol1 - ExpressをAppEngineで動かす -

概要

この記事ではAppEngineのデフォルトサービスでサンプルのExpressを動作させることを目指します。

背景

AppEngineが便利っていう話を聞いたので、AppEngineでどこまでできるのかを試す連載。 連載のゴールとしては、NuxtをBFFとしておいてAPIで処理を行うというマルチサービスの構成。

AppEngineの準備

  1. GCPでプロジェクトの作成
  2. gcloudコマンドのインストール
  3. gcloud initでプロジェクトの指定

gcloud initでデプロイ対象のプロジェクトを選択できるので行っておく。 ※これを行わない場合はprojectオプションで都度project idを指定して実行することも可能。

> gcloud -v
Google Cloud SDK 272.0.0
beta 2019.05.17
bq 2.0.50
core 2019.11.16
gsutil 4.46`

初期プロジェクトの準備

以下からサンプルコードを取得する https://cloud.google.com/appengine/docs/standard/nodejs/quickstart?hl=ja#download_the_sample_code

> git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
Cloning into 'nodejs-docs-samples'...
remote: Enumerating objects: 17475, done.
remote: Total 17475 (delta 0), reused 0 (delta 0), pack-reused 17475
Receiving objects: 100% (17475/17475), 15.33 MiB | 212.00 KiB/s, done.
Resolving deltas: 100% (11409/11409), done.

AppEngine用のディレクトリに移動する。

> cd nodejs-docs-samples/appengine/hello-world/standard

ディレクトリの構成はこんな感じ。

> ls
README.md    app.js       app.yaml     package.json test

app.yamlがAppEngineの挙動指定のファイル。 中身としては runtime: nodejs10 が指定されている。 スタンダード環境なので、動作がNodeJSのv10なんだよね。

> cat app.yaml
# Copyright 2017, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START gae_quickstart_yaml]
runtime: nodejs10
# [END gae_quickstart_yaml]

次は実行する app.js の中身。 至って普通のExpressのアプリだが、const PORT = process.env.PORT || 8080でポートを環境変数から受け取れるようにしている。 AppEngineはPORTを指定して起動するので、環境変数から受け取れるようにしないとサービスの疎通ができないのだ。

> cat app.js
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START gae_node_request_example]
const express = require('express');

const app = express();

app.get('/', (req, res) => {
  res
    .status(200)
    .send('Hello, world!')
    .end();
});

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

module.exports = app;

最後にpackage.json. scripts.startnode app.jsが指定されており、起動時にapp.jsを実行するようになっている。

> cat package.json
{
  "name": "appengine-hello-world",
  "description": "Simple Hello World Node.js sample for Google App Engine Standard Environment.",
  "version": "0.0.1",
  "private": true,
  "license": "Apache-2.0",
  "author": "Google Inc.",
  "repository": {
    "type": "git",
    "url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
  },
  "engines": {
    "node": ">=8.0.0"
  },
  "scripts": {
    "start": "node app.js",
    "test": "mocha --exit test/*.test.js"
  },
  "dependencies": {
    "express": "^4.16.3"
  },
  "devDependencies": {
    "mocha": "^6.1.4",
    "supertest": "^4.0.2"
  }
}

こいつをデプロイしてみる。 deployの内容がCLI上で確認できる。

> gcloud app deploy
Services to deploy:

descriptor:      [/Users/mizuki/workspace/20191201-example-appengine/nodejs-docs-samples/appengine/hello-world/standard/app.yaml]
source:          [/Users/mizuki/workspace/20191201-example-appengine/nodejs-docs-samples/appengine/hello-world/standard]
target project:  [astral-web-260712]
target service:  [default]
target version:  [20191201t220456]
target url:      [https://astral-web-260712.appspot.com]


Do you want to continue (Y/n)?

プロジェクトやソースが適切なのを確認する。 問題ないので、yを押してEnter。

Do you want to continue (Y/n)?  y

Beginning deployment of service [default]...
Created .gcloudignore file. See `gcloud topic gcloudignore` for details.
╔════════════════════════════════════════════════════════════╗
╠═ Uploading 6 files to Google Cloud Storage                ═╣
╚════════════════════════════════════════════════════════════╝
File upload done.
Updating service [default]...⠧

deploy中... 暫く待つ。 暫く待つと、deploy結果が出てくる。

File upload done.
Updating service [default]...done.
Setting traffic split for service [default]...done.
Deployed service [default] to [https://astral-web-260712.appspot.com]

You can stream logs from the command line by running:
  $ gcloud app logs tail -s default

To view your application in the web browser run:
  $ gcloud app browse

gcloud app logs tail -s default を実行すると defaultサービスのログをtailしてくれる。 gcloud app browseを実行すると、ブラウザでサービスを開いてくれる。

面倒な人はcurlで確認する

> curl https://astral-web-260712.appspot.com
Hello, world!%

アプリが動作していることがわかった。