本教程适用于以下操作系统版本

  • Ubuntu 22.04(Jammy Jellyfish)
  • Ubuntu 20.04(Focal Fossa)

本页内容

  • 先决条件
  • 开始之前
  • 安装 Node.js
  • 安装 Create React App 工具
  • 创建示例 React 应用
  • 为 React 应用创建 Systemd 服务
  • 配置 Nginx 作为反向代理
  • 使用 Let's Encrypt 保护 React.js
  • 访问 React 应用 Web 界面
  • 总结

React.js 是一个由 Facebook 于 2011 年开发的免费开源 JavaScript 框架。它用于构建可复用的 UI 组件,并以最少的代码帮助用户快速高效地创建丰富且引人入胜的 Web 应用。借助 React,你可以构建交互式 Web 界面,并由小型且独立的片段组合出复杂的 UI。它使用虚拟 DOM(Virtual DOM),使应用运行更快速。它提供了许多特性,例如虚拟 DOM(Virtual DOM)、单向数据绑定(One-way Data Binding)、组件(Components)、JSX、条件语句(Conditional Statements)等。

在本教程中,我们将向你展示如何在 Ubuntu 22.04 上安装 React.js。

先决条件

  • 一台运行 Ubuntu 22.04 的服务器。
  • 一个已指向你服务器 IP 的有效域名。
  • 服务器上已配置 root 密码。

开始之前

首先,你需要将系统软件包更新到最新版本。你可以使用以下命令进行更新:

apt-get update -y
apt-get upgrade -y

所有软件包更新完成后,运行以下命令安装其他所需依赖:

apt-get install curl gnupg2 -y

所有依赖安装完成后,你可以继续下一步。

安装 Node.js

接下来,你需要在服务器上安装 Node.js。默认情况下,Ubuntu 22.04 标准软件仓库中不提供最新版本的 Node.js。因此你需要从 Node.js 官方仓库安装 Node.js。

首先,使用以下命令添加 Node.js 仓库:

curl -sL https://deb.nodesource.com/setup_18.x | bash -

接下来,运行以下命令将 Node.js 安装到你的系统:

apt-get install nodejs -y

安装 Node.js 后,使用以下命令将 NPM 更新到最新版本:

npm install npm@latest -g

你应该会看到以下输出:

removed 14 packages, changed 73 packages, and audited 223 packages in 3s

14 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

接下来,使用以下命令验证已安装的 Node.js 版本:

node -v

你应该会看到以下输出:

v18.12.1

完成后,你可以继续下一步。

安装 Create React App 工具

Create React App 是一个 CLI 工具,可帮助用户节省设置和配置的时间。你只需运行一条命令,Create React App 就会搭建好启动项目所需的所有工具。

你可以使用以下命令安装 Create React App 工具:

npm install -g create-react-app

完成后,你可以继续下一步。

创建示例 React 应用

在本节中,我们将使用 Create React App 工具创建一个示例 React 应用。

首先,切换到 /opt 目录,并使用以下命令创建你的第一个项目:

cd /opt
create-react-app reactapp

你应该会看到以下输出:

Success! Created reactapp at /opt/reactapp
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd reactapp
  npm start

Happy hacking!

接下来,切换到你的项目目录,并使用以下命令启动你的应用:

cd /opt/reactapp
npm start

你应该会看到以下输出:

Compiled successfully!

You can now view reactapp in the browser.

  http://localhost:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully

按 CTRL+C 停止应用。我们将创建一个 systemd 服务文件来管理该 React 应用。

为 React 应用创建 Systemd 服务

接下来,你需要为你的 React 应用创建一个 systemd 服务。你可以使用以下命令来创建:

nano /lib/systemd/system/react.service

添加以下内容:

[Service]
Type=simple
User=root
Restart=on-failure
WorkingDirectory=/opt/reactapp
ExecStart=npm start -- --port=3000

保存并关闭文件,然后使用以下命令重新加载 systemd 守护进程:

systemctl daemon-reload

接下来,运行以下命令启动 React 服务并使其在系统重启时自动启动:

systemctl start react
systemctl enable react

你可以使用以下命令验证 React 服务的状态:

systemctl status react

你应该会看到以下输出:

? react.service
     Loaded: loaded (/lib/systemd/system/react.service; static)
     Active: active (running) since Sun 2022-11-20 11:18:50 UTC; 6s ago
   Main PID: 76129 (npm start --por)
      Tasks: 30 (limit: 2242)
     Memory: 250.9M
        CPU: 4.663s
     CGroup: /system.slice/react.service
             ??76129 "npm start --port=3000" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
             ??76140 sh -c "react-scripts start --port=3000"
             ??76141 node /opt/reactapp/node_modules/.bin/react-scripts start --port=3000
             ??76148 /usr/bin/node /opt/reactapp/node_modules/react-scripts/scripts/start.js --port=3000

Nov 20 11:18:54 ubuntu2204 npm[76148]: (node:76148) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddl>
Nov 20 11:18:54 ubuntu2204 npm[76148]: (Use `node --trace-deprecation ...` to show where the warning was created)
Nov 20 11:18:54 ubuntu2204 npm[76148]: (node:76148) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMid>
Nov 20 11:18:54 ubuntu2204 npm[76148]: Starting the development server...
Nov 20 11:18:55 ubuntu2204 npm[76148]: Compiled successfully!
Nov 20 11:18:55 ubuntu2204 npm[76148]: You can now view reactapp in the browser.
Nov 20 11:18:55 ubuntu2204 npm[76148]:   http://localhost:3000
Nov 20 11:18:55 ubuntu2204 npm[76148]: Note that the development build is not optimized.
Nov 20 11:18:55 ubuntu2204 npm[76148]: To create a production build, use npm run build.
Nov 20 11:18:55 ubuntu2204 npm[76148]: webpack compiled successfully

完成后,你可以继续下一步。

配置 Nginx 作为反向代理

将 Nginx 安装并配置为 React 应用的反向代理是个好主意,这样你就可以通过 80 端口访问你的应用。

首先,使用以下命令安装 Nginx 软件包:

apt-get install nginx -y

Nginx 安装完成后,创建一个新的 Nginx 虚拟主机配置文件:

nano /etc/nginx/sites-available/reactjs.conf

添加以下内容:

upstream backend {
  server localhost:3000;
}

server {
    listen 80;
    server_name reactjs.example.com;

    location / {
        proxy_pass http://backend/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forward-Proto http;
        proxy_set_header X-Nginx-Proxy true;

        proxy_redirect off;
    }
}

保存并关闭文件,然后使用以下命令启用该 Nginx 虚拟主机:

ln -s /etc/nginx/sites-available/reactjs.conf /etc/nginx/sites-enabled/

接下来,运行以下命令检查 Nginx 是否存在语法错误:

nginx -t

你应该会看到以下输出:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

最后,重启 Nginx 服务以使更改生效:

systemctl restart nginx

你也可以使用以下命令验证 Nginx 服务状态:

systemctl status nginx

你应该会看到以下输出:

? nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-11-20 11:20:17 UTC; 6s ago
       Docs: man:nginx(8)
    Process: 76760 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 76762 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 76763 (nginx)
      Tasks: 2 (limit: 2242)
     Memory: 2.6M
        CPU: 32ms
     CGroup: /system.slice/nginx.service
             ??76763 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             ??76764 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

Nov 20 11:20:17 ubuntu2204 systemd[1]: Starting A high performance web server and a reverse proxy server...
Nov 20 11:20:17 ubuntu2204 systemd[1]: Started A high performance web server and a reverse proxy server.

至此,Nginx 已安装并配置为托管 React 应用。你现在可以继续下一步。

使用 Let's Encrypt 保护 React.js

接下来,你需要安装 Certbot 客户端软件包,以便安装和管理 Let's Encrypt SSL。

首先,使用以下命令安装 Certbot:

apt-get install python3-certbot-nginx -y

安装完成后,运行以下命令为你的网站安装 Let's Encrypt SSL:

certbot --nginx -d reactjs.example.com

系统会要求你提供有效的电子邮件地址并接受服务条款,如下所示:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): 
[email protected]


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for reactjs.example.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/fuel.conf

接下来,选择是否将 HTTP 流量重定向到 HTTPS,如下所示:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2

输入 2 并按 Enter 完成安装。你应该会看到以下输出:

Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/fuel.conf

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://reactjs.example.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=reactjs.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/reactjs.example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/reactjs.example.com/privkey.pem
   Your cert will expire on 2023-02-20. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

 - We were unable to subscribe you the EFF mailing list because your
   e-mail address appears to be invalid. You can try again later by
   visiting https://act.eff.org.

现在,你的 React.js Web 应用已通过 Let's Encrypt SSL 受到保护。

访问 React 应用 Web 界面

现在,打开你的 Web 浏览器并输入 URL https://reactjs.example.com。你将被重定向到如下屏幕所示的 React.js Web 界面:

在 Ubuntu 22.04 系统上安装与配置 ReactJS 开发框架

总结

恭喜!你已成功在 Ubuntu 22.04 服务器上安装并配置了 React.js。你现在可以开始构建自己的 React 应用并将其托管到生产环境中。如果你有任何疑问,欢迎随时向我提问。