如何将Google Compute Engine配置为对Node.js服务器使用HTTPS?

Lov*_*rma 5 ssl node.js socket.io google-compute-engine gcloud

我想在https / SSL的Google计算引擎中运行nodejs&socket.io服务器。

我从https://cloud.google.com/compute/docs/load-balancing/http/ssl-certificates安装了自签名证书。

现在,如何使nodejs服务器使用https协议?

谢谢,

Lov*_*rma 5

下面是我在 nodejs 中用于 HTTPS 的代码,

var app = require('express')();
var https = require('https');
var fs = require('fs');
var PORT = 443;

var options = {
  key: fs.readFileSync('XYZ.key'),
  cert: fs.readFileSync('ABC.crt')
};

var server = https.createServer(options, app).listen(PORT, function () {
  console.log("Express listening on port " + PORT);
});

// Post request.
var req_res = function (req, res) {
  console.log("[200] " + req.url);
  var fullBody = '';

  // Read post data.
  req.on('data', function (chunk) {
    fullBody += chunk.toString();

    if (fullBody.length > 1e6) {
      // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
      req.connection.destroy();
    }
  });

  // Send response.
  req.on('end', function () {
    // empty 200 OK response for now
    res.writeHead(200, {
      'Content-Type': 'application/json'
    });
    res.end(JSON.stringify({
      'success': true
    }));
  });
};

// Hello World
app.get('/*', function (req, res) {
  res.status(200).send('Hello World...');
});

// Post request to receive notifications.
app.post('/post', req_res);
Run Code Online (Sandbox Code Playgroud)

关于谷歌计算引擎,您只需要从防火墙启用 443 端口。

gcloud compute firewall-rules create allow-https --description "https server" --allow tcp:443 --format json
Run Code Online (Sandbox Code Playgroud)