GAE Standard環境のNode.jsでリバースプロキシ構築

SSLのリバースプロキシが欲しかったのでメモ

HTTPS -> GAE (myproject.appspot.com) -> HTTP -> GCE (198.51.100.1:8080)

という構成。

npm初期化してhttpとhttp-proxyをインストール

1
2
3
$ npm init
$ npm install http --save
$ npm install http-proxy --save

で、下記のファイルを用意

app.yaml

1
runtime: nodejs8

index.js

1
2
3
4
const http = require('http');
const httpProxy = require('http-proxy');
const port = process.env.PORT || 8080;
httpProxy.createProxyServer({target: 'http://198.51.100.1:8080/'}).listen(port);

package.json
package.jsonはnpm initで作るとして、起動時にindex.jsを実行したいので下記のようにscriptsフィールド内でindex.jsを指定する。

1
2
3
"scripts": {
  "start": "node index.js"
},

あとはこれをAppEngineにデプロイ。

1
$ gcloud app deploy

そしてSSLで https://myproject.appspot.com/ にアクセスするとリクエストが http://198.51.100.1:8080/ にフォワードされる。