如何在Ubuntu云服务器上部署Node.js的生产环境?

  • 发布时间:2022-02-03 13:54:13
  • 阅读次数:1204

对于Node.js应用程序来说,安全、快速、强壮的生产环境对于用户体验来说至关重要。这篇帮助基于一台Ubuntu 20.04云服务器,介绍Node.js生产环境的部署方法,供Node.js系统管理员参考。

设置防火墙

防火墙可以确保只有指定的端口能够接收或发送数据,以减少服务器被攻击的风险。

安装防火墙。

$ sudo apt-get install ufw

允许必要的端口。

$ sudo ufw allow 80
$ sudo ufw allow 443
$ sudo ufw allow 22

启用防火墙并查看状态。

$ sudo ufw enable
$ sudo ufw status

创建应用程序

该应用程序使用Express.js框架,配合使用Helmet.js组件安全加固。安装Helmet.js组件。

$ npm i --save helmet

Node.js应用程序代码如下,文件名为server_file.js。

const express = require("express");
const helmet = require("helmet");
const app = express();
app.use(helmet());
app.listen(8080);

接下来,安装PM2来让Node.js应用程序以背景进程来运行。PM2可以在应用程序意外中止时重启,同时管理应用程序日志和监控应用程序性能。

$ sudo npm install pm2 -g
$ pm2 start server_file.js
$ pm2 startup

设置Nginx

Nginx是一款在生产环境中广泛使用的Web服务器,部署方便、运行快速、稳定强壮。Nginx集中管理全部HTTP请求,同时整合SSL、缓存、反向代理,Node.js应用程序得以自由扩展。

安装Nginx。

$ sudo apt-get install nginx

验证Nginx是否运行。

$ sudo systemctl status nginx
Active: active (running)

编辑Nginx配置文件,把HTTP请求重定向到HTTPS请求。其中example.com需要替换为实际域名。

# redirect HTTP traffic to HTTPS
server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://example.com$request_uri;
}

# HTTPS server
server {
        listen 443 ssl;
        server_name example.com;
        access_log /var/log/nginx/example.com.log;
        ssl_certificate /path/to/certificate/example.com.crt;
        ssl_certificate_key /path/to/key/example.com.key;
        location / {
            proxy_set_header HOST $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_pass http://127.0.0.1:8080; # Node.js Application
        }
}

重启Nginx使之生效。

$ sudo systemctl restart nginx

最后用浏览器访问:https://example.com 。如果能够正常访问,说明Node.js应用程序已成功部署。

【全文完】

< 上一篇:如何在Ubuntu云服务器上安装Node.js和NVM? 下一篇:如何在Ubuntu云服务器上安装和使用Composer? >