首页 > 解决方案 > 如何在实时服务器上自动运行 node js (express) 应用程序?

问题描述

我的 Angular 应用程序有类似后端的快速应用程序。如何在远程服务器上部署该应用程序并且该应用程序始终在服务器上运行?

标签: node.jsangularexpressserver

解决方案


有人说直接运行 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

https://www.freecodecamp.org/news/you-should-never-ever-run-directly-against-node-js-in-production-maybe-7fdfaed51ec6/

您可以考虑使用 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" }

推荐阅读