Установка React · 10 min read · Dec 21, 2025

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

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

В этом разделе мы создадим примерное приложение 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 на наличие синтаксических ошибок, выполнив следующую команду:

ginx -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 с помощью Let’s Encrypt

Далее вам нужно будет установить пакет клиента Certbot для установки и управления SSL Let’s Encrypt.

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

apt-get install python3-certbot-nginx -y

После завершения установки выполните следующую команду для установки SSL Let’s Encrypt на ваш веб-сайт:

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

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

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

Заключение

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

Share: X/Twitter LinkedIn

Get new posts in your inbox

No spam. Unsubscribe anytime.