LoginSignup
5
5

More than 3 years have passed since last update.

Serverless FrameworkでNode.jsのサーバーレスAPIをGCPにデプロイしてみた

Last updated at Posted at 2020-12-19



この記事は、「Google Cloud Platform Advent Calendar 2020」の19日目の記事です。

Serverless FrameworkでNode.jsのサーバーレスAPIをGCPにデプロイしてみました :tada:


事前準備


事前設定ができていれば3コマンドでデプロイできます!


はじめに、Node.jsテンプレートでプロジェクトを作成します。

sls create -t google-nodejs -p sample

画像


次に、対象プロジェクトに移動しパッケージをインストールします。

cd sample
npm install

画像


作成されたプロジェクトを確認します。今回は、「serverless.yml」のみ変更します。

package.json

{
  "name": "sample",
  "version": "0.1.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "serverless.com",
  "license": "MIT",
  "devDependencies": {
    "serverless-google-cloudfunctions": "*"
  }
}


index.js

'use strict';

exports.http = (request, response) => {
  response.status(200).send('Hello World!');
};

exports.event = (event, callback) => {
  callback();
};


serverless.yml

service: sample

provider:
    name: google
    stage: dev
    runtime: nodejs10
    region: us-central1
    project: GCPのプロジェクト名
    credentials: ~/.gcloud/keyfile.json

frameworkVersion: '2'

plugins:
    - serverless-google-cloudfunctions

package:
    exclude:
        - node_modules/**
        - .gitignore
        - .git/**

functions:
    first:
        handler: http
        events:
            - http: path

対象のGCPのプロジェクト名に変更。

project: GCPのプロジェクト名


プロジェクトが完成したらGCPにデプロイします。

sls deploy

画像


デプロイ後に、GCPのコンソールでCloud Functionsが作成されているのを確認してみます。

画像


「allUsers」を割り当ててAPIにアクセスできるように設定します。

画像

画像


表示されました :tada:

画像


Serverless FrameworkでNode.jsのサーバーレスAPIをGCPにデプロイできました :thumbsup:

Serverless Frameworkを利用することで、手軽にGCPにサーバーレス環境をデプロイできました :bulb: 色々と設定できそうなので今後も試していきたいと思います :grinning:

以前にZappaでためした記事、「ZappaでDBもパッケージしたサーバーレスAPIを構築してみた」もあるので比較してみて頂ければと思います。


Serverless Frameworkについて、他にも記事を書いています。よろしければぜひ :bow:
tags - Serverless Framework

やってみたシリーズ :grinning:
tags - Try




book

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5