如何在Ubuntu 20.04上为生产设置Node.js应用程序

介绍 (Introduction)

Node.js is an open-source JavaScript runtime environment for building server-side and networking applications. The platform runs on Linux, macOS, FreeBSD, and Windows. Though you can run Node.js applications at the command line, this tutorial will focus on running them as a service. This means that they will restart on reboot or failure and are safe for use in a production environment.

Node.js是用于构建服务器端和网络应用程序的开源JavaScript运行时环境。 该平台可在Linux,macOS,FreeBSD和Windows上运行。 尽管您可以在命令行上运行Node.js应用程序,但本教程将着重于将它们作为服务运行。 这意味着它们将在重新启动或发生故障时重新启动,并且可以在生产环境中安全使用。

In this tutorial, you will set up a production-ready Node.js environment on a single Ubuntu 20.04 server. This server will run a Node.js application managed by PM2, and provide users with secure access to the application through an Nginx reverse proxy. The Nginx server will offer HTTPS using a free certificate provided by Let’s Encrypt.

在本教程中,您将在单个Ubuntu 20.04服务器上设置生产就绪的Node.js环境。 该服务器将运行由PM2管理的Node.js应用程序,并通过Nginx反向代理为用户提供对该应用程序的安全访问。 Nginx服务器将使用Let's Encrypt提供的免费证书提供HTTPS。

先决条件 (Prerequisites)

This guide assumes that you have the following:

本指南假定您具有以下条件:

When you’ve completed the prerequisites, you will have a server serving your domain’s default placeholder page at https://example.com/.

完成前提条件后,您将在https:// example.com /拥有一台服务器,服务于您域的默认占位符页面。

第1步-安装Node.js (Step 1 — Installing Node.js)

Let’s begin by installing the latest LTS release of Node.js, using the NodeSource package archives.

让我们开始使用NodeSource软件包档案安装最新的LTS版本的Node.js。

First, install the NodeSource PPA in order to get access to its contents. Make sure you’re in your home directory, and use curl to retrieve the installation script for the most recent LTS version of Node.js from its archives.

首先,安装NodeSource PPA以便访问其内容。 确保您位于主目录中,并使用curl从其归档文件中检索Node.js的最新LTS版本的安装脚本。

  • cd ~

    光盘〜
  • curl -sL https://deb.nodesource.com/setup_14.x -o nodesource_setup.sh

    curl -sL https://deb.nodesource.com/setup_ 14 .x -o nodesource_setup.sh

You can inspect the contents of this script with nano or your preferred text editor:

您可以使用nano或您喜欢的文本编辑器检查此脚本的内容:

  • nano nodesource_setup.sh

    纳米节点source_setup.sh

When you’re done inspecting the script, run it under sudo:

检查完脚本后,在sudo下运行它:

  • sudo bash nodesource_setup.sh

    须藤bash nodesource_setup.sh

The PPA will be added to your configuration and your local package cache will be updated automatically. After running the setup script from Nodesource, you can install the Node.js package:

PPA将添加到您的配置中,并且本地软件包缓存将自动更新。 从Nodesource运行安装脚本后,可以安装Node.js软件包:

  • sudo apt install nodejs

    sudo apt安装nodejs

To check which version of Node.js you have installed after these initial steps, type:

要检查在完成这些初始步骤后已安装的Node.js版本,请输入:

  • nodejs -v

    节点-v

   
   
Output
v14.4.0

Note: When installing from the NodeSource PPA, the Node.js executable is called nodejs, rather than node.

注意:从NodeSource PPA安装时,Node.js可执行文件称为nodejs ,而不是node

The nodejs package contains the nodejs binary as well as npm, a package manager for Node modules, so you don’t need to install npm separately.

nodejs软件包包含nodejs二进制文件以及npm (用于Node模块的软件包管理器),因此您无需单独安装npm

npm uses a configuration file in your home directory to keep track of updates. It will be created the first time you run npm. Execute this command to verify that npm is installed and to create the configuration file:

npm使用主目录中的配置文件来跟踪更新。 它将在您第一次运行npm时创建。 执行以下命令以验证是否已安装npm并创建配置文件:

  • npm -v

    npm -v

   
   
Output
6.14.5

In order for some npm packages to work (those that require compiling code from source, for example), you will need to install the build-essential package:

为了使某些npm软件包(例如那些需要从源代码编译代码的软件包)起作用,您将需要安装build-essential软件包:

  • sudo apt install build-essential

    须藤apt install build-essential

You now have the necessary tools to work with npm packages that require compiling code from source.

现在,您具有必要的工具来处理需要从源代码编译代码的npm软件包。

With the Node.js runtime installed, let’s move on to writing a Node.js application.

安装了Node.js运行时之后,让我们继续编写Node.js应用程序。

第2步-创建Node.js应用程序 (Step 2 — Creating a Node.js Application)

Let’s write a Hello World application that returns “Hello World” to any HTTP requests. This sample application will help you get Node.js set up. You can replace it with your own application — just make sure that you modify your application to listen on the appropriate IP addresses and ports.

让我们编写一个Hello World应用程序,该应用程序向任何HTTP请求返回“ Hello World”。 该示例应用程序将帮助您设置Node.js。 您可以用自己的应用程序替换它-只需确保您修改了应用程序以侦听适当的IP地址和端口即可。

First, let’s create a sample application called hello.js:

首先,让我们创建一个名为hello.js的示例应用程序:

  • cd ~

    光盘〜
  • nano hello.js

    纳米hello.js

Insert the following code into the file:

将以下代码插入文件:

~/hello.js
〜/ hello.js
const http = require('http');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Save the file and exit the editor.

保存文件并退出编辑器。

This Node.js application listens on the specified address (localhost) and port (3000), and returns “Hello World!” with a 200 HTTP success code. Since we’re listening on localhost, remote clients won’t be able to connect to our application.

此Node.js应用程序侦听指定的地址( localhost )和端口( 3000 ),并返回“ Hello World!”。 具有200 HTTP成功代码。 由于我们正在监听localhost ,因此远程客户端将无法连接到我们的应用程序。

To test your application, type:

要测试您的应用程序,请输入:

  • node hello.js

    节点hello.js

You will receive the following output:

您将收到以下输出:


   
   
Output
Server running at http://localhost:3000/

Note: Running a Node.js application in this manner will block additional commands until the application is killed by pressing CTRL+C.

注意:以这种方式运行Node.js应用程序将阻止其他命令,直到按CTRL+C将其杀死。

To test the application, open another terminal session on your server, and connect to localhost with curl:

要测试应用程序,请在服务器上打开另一个终端会话,然后使用curl连接到localhost

  • curl http://localhost:3000

    卷曲http:// localhost: 3000

If you get the following output, the application is working properly and listening on the correct address and port:

如果获得以下输出,则说明应用程序正常运行并且正在侦听正确的地址和端口:


   
   
Output
Hello World!

If you do not get the expected output, make sure that your Node.js application is running and configured to listen on the proper address and port.

如果未获得预期的输出,请确保您的Node.js应用程序正在运行并配置为侦听正确的地址和端口。

Once you’re sure it’s working, kill the application (if you haven’t already) by pressing CTRL+C.

确定运行正常后,请按CTRL+C应用程序(如果尚未运行)。

步骤3 —安装PM2 (Step 3 — Installing PM2)

Next let’s install PM2, a process manager for Node.js applications. PM2 makes it possible to daemonize applications so that they will run in the background as a service.

接下来,让我们安装PM2,它是Node.js应用程序的流程管理器。 PM2可以守护应用程序,以便它们作为服务在后台运行。

Use npm to install the latest version of PM2 on your server:

使用npm在您的服务器上安装最新版本的PM2:

  • sudo npm install pm2@latest -g

    须藤npm install pm2 @ latest -g

The -g option tells npm to install the module globally, so that it’s available system-wide.

-g选项告诉npm 全局安装模块,以便在整个系统范围内可用。

Let’s first use the pm2 start command to run your application, hello.js, in the background:

首先让我们使用hello.js pm2 start命令在后台运行您的应用程序hello.js

  • pm2 start hello.js

    pm2启动hello.js

This also adds your application to PM2’s process list, which is outputted every time you start an application:

这还将您的应用程序添加到PM2的进程列表中,该列表在每次启动应用程序时输出:


   
   
Output
... [PM2] Spawning PM2 daemon with pm2_home=/home/sammy/.pm2 [PM2] PM2 Successfully daemonized [PM2] Starting /home/sammy/hello.js in fork_mode (1 instance) [PM2] Done. ┌────┬────────────────────┬──────────┬──────┬───────────┬──────────┬──────────┐ │ id │ name │ mode │ ↺ │ status │ cpu │ memory │ ├────┼────────────────────┼──────────┼──────┼───────────┼──────────┼──────────┤ │ 0 │ hello │ fork │ 0 │ online │ 0% │ 25.2mb │ └────┴────────────────────┴──────────┴──────┴───────────┴──────────┴──────────┘

As indicated above, PM2 automatically assigns an App name (based on the filename, without the .js extension) and a PM2 id. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

如上所述,PM2自动分配一个App name (基于文件名,不带.js扩展名)和一个PM2 id 。 PM2还维护其他信息,例如进程的PID ,其当前状态和内存使用情况。

Applications that are running under PM2 will be restarted automatically if the application crashes or is killed, but we can take an additional step to get the application to launch on system startup using the startup subcommand. This subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots:

如果PM2下运行的应用程序崩溃或被杀死,它将自动重新启动,但是我们可以采取额外的步骤,使用startup子命令使该应用程序在系统启动时startup 。 此子命令生成并配置启动脚本,以在服务器启动时启动PM2及其托管进程:

  • pm2 startup systemd

    pm2启动系统

The last line of the resulting output will include a command to run with superuser privileges in order to set PM2 to start on boot:

结果输出的最后一行将包含一个以超级用户特权运行的命令,以便将PM2设置为在启动时启动:


   
   
Output
[PM2] Init System found: systemd sammy [PM2] To setup the Startup Script, copy/paste the following command: sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u sammy --hp /home/sammy

Run the command from the output, with your username in place of sammy:

从您的用户名代替sammy的输出中运行命令:

  • sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u sammy --hp /home/sammy

    sudo env PATH = $ PATH:/ usr / bin / usr / lib / node_modules / pm2 / bin / pm2启动系统d -u sammy --hp / home / sammy

As an additional step, we can save the PM2 process list and corresponding environments:

另外,我们可以保存PM2流程列表和相应的环境:

  • pm2 save

    pm2保存

You have now created a systemd unit that runs pm2 for your user on boot. This pm2 instance, in turn, runs hello.js.

现在,您已经创建了一个在引导时为用户运行pm2的systemd 单元 。 该pm2实例依次运行hello.js

Start the service with systemctl:

使用systemctl启动服务:

  • sudo systemctl start pm2-sammy

    须藤systemctl启动pm2- sammy

If at this point you encounter an error, you may need to reboot, which you can achieve with sudo reboot.

如果此时遇到错误,则可能需要重新引导,这可以通过sudo reboot实现。

Check the status of the systemd unit:

检查系统单元的状态:

  • systemctl status pm2-sammy

    systemctl状态pm2- sammy

For a detailed overview of systemd, please review Systemd Essentials: Working with Services, Units, and the Journal.

有关systemd的详细概述,请查看Systemd Essentials:使用服务,单位和期刊

In addition to those we have covered, PM2 provides many subcommands that allow you to manage or look up information about your applications.

除了我们已经介绍的内容之外,PM2还提供了许多子命令,这些子命令使您可以管理或查找有关应用程序的信息。

Stop an application with this command (specify the PM2 App name or id):

使用以下命令停止应用程序(指定PM2 App nameid ):

  • pm2 stop app_name_or_id

    pm2停止app_name_or_id

Restart an application:

重新启动应用程序:

  • pm2 restart app_name_or_id

    pm2重新启动app_name_or_id

List the applications currently managed by PM2:

列出当前由PM2管理的应用程序:

  • pm2 list

    pm2清单

Get information about a specific application using its App name:

使用其App name获取有关特定应用的信息:

  • pm2 info app_name

    pm2信息app_name

The PM2 process monitor can be pulled up with the monit subcommand. This displays the application status, CPU, and memory usage:

可以使用monit子命令拉起PM2过程监视器。 这将显示应用程序状态,CPU和内存使用情况:

  • pm2 monit

    pm2 monit

Note that running pm2 without any arguments will also display a help page with example usage.

请注意,不带任何参数运行pm2还将显示一个带有示例用法的帮助页面。

Now that your Node.js application is running and managed by PM2, let’s set up the reverse proxy.

现在,您的Node.js应用程序正在由PM2运行和管理,让我们设置反向代理。

步骤4 —将Nginx设置为反向代理服务器 (Step 4 — Setting Up Nginx as a Reverse Proxy Server)

Your application is running and listening on localhost, but you need to set up a way for your users to access it. We will set up the Nginx web server as a reverse proxy for this purpose.

您的应用程序正在localhost上运行并在监听,但是您需要设置一种供用户访问它的方法。 为此,我们将Nginx Web服务器设置为反向代理。

In the prerequisite tutorial, you set up your Nginx configuration in the /etc/nginx/sites-available/example.com file. Open this file for editing:

在先决条件教程中,您可以在/etc/nginx/sites-available/ example.com文件中设置Nginx配置。 打开此文件进行编辑:

  • sudo nano /etc/nginx/sites-available/example.com

    须藤纳米/ etc / nginx / sites-available / example.com

Within the server block, you should have an existing location / block. Replace the contents of that block with the following configuration. If your application is set to listen on a different port, update the highlighted portion to the correct port number:

server块内,您​​应该有一个现有的location /块。 用以下配置替换该块的内容。 如果您的应用程序设置为在其他端口上侦听,请将突出显示的部分更新为正确的端口号:

/etc/nginx/sites-available/example.com
/etc/nginx/sites-available/example.com
server {
...
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
...
}

This configures the server to respond to requests at its root. Assuming our server is available at example.com, accessing https://example.com/ via a web browser would send the request to hello.js, listening on port 3000 at localhost.

这会将服务器配置为响应其根目录下的请求。 假设我们的服务器在example.com上可用,则通过Web浏览器访问https:// example.com /会将请求发送到hello.js ,侦听localhost端口3000

You can add additional location blocks to the same server block to provide access to other applications on the same server. For example, if you were also running another Node.js application on port 3001, you could add this location block to allow access to it via https://example.com/app2:

您可以将其他location块添加到同一服务器块,以提供对同一服务器上其他应用程序的访问。 例如,如果您还在端口3001上运行另一个Node.js应用程序,则可以添加此位置块以允许通过https:// example.com / app2对其进行访问:

/etc/nginx/sites-available/example.com — Optional
/etc/nginx/sites-available/example.com-可选
server {
...
    location /app2 {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
...
}

Once you are done adding the location blocks for your applications, save the file and exit your editor.

完成为应用程序添加位置块后,保存文件并退出编辑器。

Make sure you didn’t introduce any syntax errors by typing:

通过输入以下内容确保您没有引入任何语法错误:

  • sudo nginx -t

    须藤Nginx -t

Restart Nginx:

重新启动Nginx:

  • sudo systemctl restart nginx

    sudo systemctl重启nginx

Assuming that your Node.js application is running, and your application and Nginx configurations are correct, you should now be able to access your application via the Nginx reverse proxy. Try it out by accessing your server’s URL (its public IP address or domain name).

假设您的Node.js应用程序正在运行,并且您的应用程序和Nginx配置正确,那么您现在应该能够通过Nginx反向代理访问您的应用程序。 通过访问服务器的URL(公共IP地址或域名)进行尝试。

结论 (Conclusion)

Congratulations! You now have your Node.js application running behind an Nginx reverse proxy on an Ubuntu 20.04 server. This reverse proxy setup is flexible enough to provide your users access to other applications or static web content that you want to share.

恭喜你! 现在,您的Node.js应用程序在Ubuntu 20.04服务器上的Nginx反向代理后面运行。 这种反向代理设置足够灵活,可以为您的用户提供对您要共享的其他应用程序或静态Web内容的访问权限。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-20-04

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值