node.js - 如何在实时服务器上自动运行 node js (express) 应用程序?
问题描述
我的 Angular 应用程序有类似后端的快速应用程序。如何在远程服务器上部署该应用程序并且该应用程序始终在服务器上运行?
解决方案
有人说直接运行 node 作为你的服务器不是一个好主意,有人说这没关系。无论如何:
有多种方法可以实现这一目标:
码头工人
基于节点创建 Dockerfile,复制您的应用程序并将构建的映像作为容器启动并重启(docker-service)。它可能是这样的(非常简化):
FROM node:latest
COPY ./app:/APP_DIRECTORY
RUN node /APP_DIRECTORY/index.js
systemd(在 Linux 系统上)
直接在您的操作系统上创建服务并让它自动重启。更多信息:https ://nodesource.com/blog/running-your-node-js-app-with-systemd-part-1/
pm2
您可以考虑使用 nginx 作为节点应用程序的代理的建议。更多信息在这里(这个链接也有一个 pm2 的例子):https ://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on -ubuntu-16-04
编辑:2020-01-27
使用 fastify 和 pm2 的示例
由于这个问题的作者希望我提供一个 pm2 的示例,所以我们开始:
先决条件
mkdir pm2-test
cd pm2-test
npm init -y
npm install --save fastify
npm install --save-dev nodemon
npm install -g pm2
touch index.js
创建服务器
// package.json -> scripts section
[...]
"scripts": {
"start": "pm2 start index.js",
"dev": "nodemon index.js"
},
[...]
// index.js -> copied from fastify's example on github
// Require the framework and instantiate it
const fastify = require('fastify')({
logger: true
})
// Declare a route
fastify.get('/', (request, reply) => {
reply.send({ hello: 'world' })
})
// Run the server!
fastify.listen(3000, (err, address) => {
if (err) throw err
fastify.log.info(`server listening on ${address}`)
})
启动 pm2 进程
npm start
结果
// in console:
╰─ npm start
> pm2-test@1.0.0 start /Volumes/Samsung_T5/private/pm2-test
> pm2 start index.js
[PM2] Starting /Volumes/Samsung_T5/private/pm2-test/index.js in
fork_mode (1 instance)
[PM2] Done.
/** SOME BIG TABLE DISPLAYS ALL OF YOUR RUNNING/STOPPED INSTANCES **/
// In the browser -> localhost:3000
{ "hello": "world" }
推荐阅读
- javascript - .then 块内的奇怪设置状态行为
- javascript - 不能从另一个页面链接到包含书签的 innerHTML
- python - TypeError:“_SessionRequestContextManager”对象不可迭代
- javascript - Angular Firebase 期望验证器返回 Promise 或 Observable
- c - 通过将二进制文件反转为源代码来对二进制文件进行模糊测试怎么样?
- ansible - 当 Ansible 控制器在 AWS VM 上时,是否可以从我的 mac 运行剧本?
- c# - Visual Studio 2019 WPF 设计器不会显示自定义控件
- java - Java 8 - 生成列表的幂集
- javascript - 如何使用 ANTd 在 React 中创建动态表单输入字段
- javascript - 相同的代码在不同的 IDE 中不起作用 - html,css