如何configurationGoogle Compute Engine以使用HTTPS for nodejs服务器?

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

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

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

谢谢,

以下是我在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); 

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

 gcloud compute firewall-rules create allow-https --description "https server" --allow tcp:443 --format json 

您需要一些configurationnodeJS服务器来使用HTTPs的东西。 我build议Nginx( http://nginx.org/en/docs/http/configuring_https_servers.html )设置https端口443连接,以在nginx层终止。 然后使用Nginx中的proxy_pass指令将所有这些连接代理到您的NodeJS服务器。 你也可以在Nginx中使用upstream指令。

你也必须在non-https设置中这样做,因为nodeJS不应该监听默认的80端口,因为它是一个系统端口,并且nodeJS将不允许你启动这个进程,除非你运行sudo (再次不推荐)。