Поиск по сайту:

Как установить ReactJS с Nginx на Ubuntu 22.04


Это руководство существует для этих версий ОС

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

На этой странице

  1. Предпосылки
  2. Начало работы
  3. Установите Node.js
  4. Установите инструмент создания приложения React
  5. Создание примера приложения React
  6. Создание службы Systemd для приложения React
  7. Настройка Nginx в качестве обратного прокси-сервера
  8. Защитите React.js с помощью Lets Encrypt
  9. Доступ к веб-интерфейсу приложения React
  10. Заключение

React.js — это бесплатная среда JavaScript с открытым исходным кодом, разработанная Facebook в 2011 году. Она используется для создания многократно используемых компонентов пользовательского интерфейса и помогает пользователям быстро и эффективно создавать многофункциональные и привлекательные веб-приложения с минимальным кодированием. С помощью React вы можете создать интерактивный веб-интерфейс и составить сложные пользовательские интерфейсы из небольших и изолированных частей. Он использует Virtual DOM, что делает приложение быстрым. Он предоставляет множество функций, таких как Virtual DOM, односторонняя привязка данных, компоненты, JSX, условные операторы и многие другие.

В этом руководстве мы покажем вам, как установить React.js в Ubuntu 22.04.

Предпосылки

  • Сервер под управлением Ubuntu 22.04.
  • Действительное доменное имя, указанное с IP-адресом вашего сервера.
  • На сервере настроен пароль root.

Начиная

Во-первых, вам нужно будет обновить системные пакеты до последней версии. Вы можете обновить их с помощью следующей команды:

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

Как только все пакеты будут обновлены, выполните следующую команду, чтобы установить другие необходимые зависимости:

apt-get install curl gnupg2 -y

После установки всех зависимостей можно переходить к следующему шагу.

Установите Node.js

Далее вам нужно будет установить Node.js на свой сервер. По умолчанию последняя версия Node.js недоступна в стандартном репозитории Ubuntu 22.04. Поэтому вам нужно будет установить 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  -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

Как только вы закончите, вы можете перейти к следующему шагу.

Установите инструмент создания приложения React

Create React App — это инструмент командной строки, который помогает пользователям сэкономить время на установку и настройку. Вам просто нужно запустить одну команду, и приложение Create React настроит все инструменты, необходимые для запуска вашего проекта.

Вы можете установить инструмент Create React App, используя следующую команду:

npm install -g create-react-app

Как только вы закончите, вы можете перейти к следующему шагу.

Создайте образец приложения React

В этом разделе мы создадим образец приложения React с помощью инструмента Create React App.

Сначала измените каталог на /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.

Создайте службу Systemd для приложения React

Далее вам нужно будет создать службу systemd для вашего приложения React. Вы можете создать его с помощью следующей команды:

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. Теперь вы можете перейти к следующему шагу.

Защитите React.js с помощью Lets Encrypt

Затем вам нужно будет установить клиентский пакет Certbot для установки и управления Lets Encrypt SSL.

Сначала установите Certbot с помощью следующей команды:

apt-get install python3-certbot-nginx -y

После завершения установки выполните следующую команду, чтобы установить Lets 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): 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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 защищено с помощью Lets Encrypt SSL.

Доступ к веб-интерфейсу приложения React

Теперь откройте веб-браузер и введите URL-адрес https://reactjs.example.com. Вы будете перенаправлены в веб-интерфейс React.Js на следующем экране:

Заключение

Поздравляем! вы успешно установили и настроили React.Js на сервере Ubuntu 22.04. Теперь вы можете приступить к созданию собственного приложения на основе React и разместить его в производственной среде. Не стесняйтесь спрашивать меня, если у вас есть какие-либо вопросы.