Ricerca nel sito web

Come installare ReactJS con Nginx su Ubuntu 22.04


Questo tutorial esiste per queste versioni del sistema operativo

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

Su questa pagina

  1. Prerequisiti
  2. Per iniziare
  3. Installa Node.js
  4. Installa lo strumento Crea app React
  5. Crea un'applicazione React di esempio
  6. Crea un servizio Systemd per l'app React
  7. Configura Nginx come proxy inverso
  8. Proteggi React.js con Lets Encrypt
  9. Accedi all'interfaccia web dell'app React
  10. Conclusione

React.js è un framework JavaScript gratuito e open source sviluppato da Facebook nel 2011. Viene utilizzato per creare componenti dell'interfaccia utente riutilizzabili e aiuta gli utenti a creare app Web ricche e coinvolgenti in modo rapido ed efficiente con una codifica minima. Con React, puoi creare un'interfaccia web interattiva e comporre interfacce utente complesse da pezzi piccoli e isolati. Utilizza Virtual DOM che rende l'app veloce. Fornisce molte funzionalità come DOM virtuale, associazione dati unidirezionale, componenti, JSX, istruzioni condizionali e molte altre.

In questo tutorial, ti mostreremo come installare React.js su Ubuntu 22.04.

Prerequisiti

  • Un server che esegue Ubuntu 22.04.
  • Nome di dominio valido indicato con l'IP del tuo server.
  • Sul server è configurata una password di root.

Iniziare

Innanzitutto, dovrai aggiornare i tuoi pacchetti di sistema all'ultima versione. Puoi aggiornarli usando il seguente comando:

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

Una volta che tutti i pacchetti sono aggiornati, eseguire il seguente comando per installare altre dipendenze richieste:

apt-get install curl gnupg2 -y

Una volta installate tutte le dipendenze, puoi procedere al passaggio successivo.

Installa Node.js

Successivamente, dovrai installare Node.js sul tuo server. Per impostazione predefinita, l'ultima versione di Node.js non è disponibile nel repository standard di Ubuntu 22.04. Quindi dovrai installare Node.js dal repository ufficiale di Node.js.

Innanzitutto, aggiungi il repository Node.js con il seguente comando:

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

Successivamente, esegui il seguente comando per installare Node.js sul tuo sistema:

apt-get install nodejs -y

Dopo aver installato Node.js, aggiorna NPM alla versione più recente utilizzando il seguente comando:

npm install  -g

Dovresti ottenere il seguente output:

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

Successivamente, verifica la versione installata di Node.js con il seguente comando:

node -v

Dovresti ottenere il seguente output:

v18.12.1

Una volta terminato, puoi procedere al passaggio successivo.

Installa lo strumento Crea app React

Create React App è uno strumento CLI che aiuta gli utenti a risparmiare tempo per l'installazione e la configurazione. Devi solo eseguire un singolo comando e Create React App imposterà tutti gli strumenti necessari per avviare il tuo progetto.

Puoi installare lo strumento Create React App utilizzando il seguente comando:

npm install -g create-react-app

Una volta terminato, puoi procedere al passaggio successivo.

Crea un'applicazione React di esempio

In questa sezione, creeremo un'app React di esempio con lo strumento Crea app React.

Innanzitutto, cambia la directory in /opt e crea il tuo primo progetto con il seguente comando:

cd /opt
create-react-app reactapp

Dovresti vedere il seguente output:

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!

Quindi, cambia la directory nella directory del tuo progetto e avvia la tua applicazione con il seguente comando:

cd /opt/reactapp
npm start

Dovresti ottenere il seguente output:

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

Premere CTRL+C per interrompere l'applicazione. Creeremo un file di servizio systemd per gestire l'applicazione React.

Crea un servizio Systemd per l'app React

Successivamente, dovrai creare un servizio systemd per la tua app React. Puoi crearlo con il seguente comando:

nano /lib/systemd/system/react.service

Aggiungi le seguenti righe:

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

Salva e chiudi il file, quindi ricarica il demone systemd con il seguente comando:

systemctl daemon-reload

Successivamente, avvia il servizio React e abilitalo per l'avvio al riavvio del sistema eseguendo il seguente comando:

systemctl start react
systemctl enable react

Puoi verificare lo stato del servizio React con il seguente comando:

systemctl status react

Dovresti ottenere il seguente output:

? 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

Una volta terminato, puoi procedere al passaggio successivo.

Configura Nginx come proxy inverso

È una buona idea installare e configurare Nginx come proxy inverso per l'app React. Quindi puoi accedere alla tua app tramite la porta 80.

Innanzitutto, installa il pacchetto Nginx utilizzando il seguente comando:

apt-get install nginx -y

Una volta installato Nginx, crea un nuovo file di configurazione dell'host virtuale Nginx:

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

Aggiungi le seguenti righe:

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;
    }
}

Salva e chiudi il file, quindi abilita l'host virtuale Nginx con il seguente comando:

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

Successivamente, verifica Nginx per eventuali errori di sintassi eseguendo il seguente comando:

nginx -t

Dovresti ottenere il seguente output:

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

Infine, riavvia il servizio Nginx per applicare le modifiche:

systemctl restart nginx

Puoi anche verificare lo stato del servizio Nginx con il seguente comando:

systemctl status nginx

Dovresti vedere il seguente output:

? 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.

A questo punto, Nginx è installato e configurato per servire l'app React. Ora puoi procedere al passaggio successivo.

Proteggi React.js con Lets Encrypt

Successivamente, dovrai installare il pacchetto client Certbot per installare e gestire Lets Encrypt SSL.

Innanzitutto, installa Certbot con il seguente comando:

apt-get install python3-certbot-nginx -y

Al termine dell'installazione, esegui il seguente comando per installare Lets Encrypt SSL sul tuo sito web:

certbot --nginx -d reactjs.example.com

Ti verrà chiesto di fornire un indirizzo email valido e di accettare i termini di servizio come mostrato di seguito:

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

Successivamente, scegli se reindirizzare o meno il traffico HTTP su HTTPS come mostrato di seguito:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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

Digita 2 e premi Invio per completare l'installazione. Dovresti vedere il seguente output:

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.

Ora, la tua applicazione web React.js è ora protetta con Lets Encrypt SSL.

Accedi all'interfaccia Web dell'app React

Ora apri il tuo browser web e digita l'URL https://reactjs.example.com. Verrai reindirizzato all'interfaccia web di React.Js nella seguente schermata:

Conclusione

Congratulazioni! hai installato e configurato correttamente React.Js sul server Ubuntu 22.04. Ora puoi iniziare a creare la tua applicazione basata su React e ospitarla nell'ambiente di produzione. Non esitate a chiedermi se avete domande.