如何在实时服务器上自动运行Node js(express)应用程序?

时间:2020-01-17 09:02:59

标签: node.js angular express server

我的Angular应用有像后端这样的Express应用。如何在远程服务器上部署该应用程序,并且该应用程序始终在服务器上运行?

1 个答案:

答案 0 :(得分:1)

有人说直接将节点作为服务器运行不是一个好主意,而有人说没关系。无论如何:

有多种方法可以实现此目的:

Docker

基于节点创建一个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" }