Wie man ReactJS mit Nginx auf Ubuntu 22.04 installiert

React.js ist ein freies und quelloffenes JavaScript-Framework, das 2011 von Facebook entwickelt wurde. Es dient zur Erstellung wiederverwendbarer UI-Komponenten und hilft Nutzern, mit minimalem Programmieraufwand schnell und effizient reichhaltige und ansprechende Webanwendungen zu erstellen. Mit React kannst du eine interaktive Weboberfläche erstellen und komplexe Benutzeroberflächen aus kleinen und isolierten Teilen zusammensetzen. Es nutzt Virtual DOM, was die App schnell macht. Es bietet viele Funktionen wie Virtual DOM, One-way Data Binding, Components, JSX, Conditional Statements und viele mehr.

In diesem Lernprogramm zeigen wir dir, wie du React.js auf Ubuntu 22.04 installierst.

Voraussetzungen

  • Ein Server, auf dem Ubuntu 22.04 läuft.
  • Ein gültiger Domainname, der auf die IP deines Servers zeigt.
  • Ein Root-Passwort ist auf dem Server eingerichtet.

Erste Schritte

Zuerst musst du deine Systempakete auf die neueste Version aktualisieren. Du kannst sie mit dem folgenden Befehl aktualisieren:

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

Sobald alle Pakete auf dem neuesten Stand sind, führst du den folgenden Befehl aus, um andere erforderliche Abhängigkeiten zu installieren:

apt-get install curl gnupg2 -y

Sobald alle Abhängigkeiten installiert sind, kannst du mit dem nächsten Schritt fortfahren.

Node.js installieren

Als Nächstes musst du Node.js auf deinem Server installieren. Standardmäßig ist die neueste Version von Node.js nicht im Standard-Repository von Ubuntu 22.04 verfügbar. Daher musst du Node.js aus dem offiziellen Repository von Node.js installieren.

Füge zunächst das Node.js-Repository mit dem folgenden Befehl hinzu:

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

Als Nächstes führst du den folgenden Befehl aus, um Node.js auf deinem System zu installieren:

apt-get install nodejs -y

Nach der Installation von Node.js aktualisierst du den NPM mit dem folgenden Befehl auf die neueste Version:

npm install npm@latest -g

Du solltest die folgende Ausgabe erhalten:

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

Als Nächstes überprüfst du die installierte Version von Node.js mit dem folgenden Befehl:

node -v

Du solltest die folgende Ausgabe erhalten:

v18.12.1

Wenn du damit fertig bist, kannst du mit dem nächsten Schritt fortfahren.

Create React App Tool installieren

Create React App ist ein CLI-Tool, das dir hilft, Zeit bei der Einrichtung und Konfiguration zu sparen. Du musst nur einen einzigen Befehl ausführen und Create React App richtet alle Tools ein, die du für dein Projekt benötigst.

Du kannst das Create React App Tool mit dem folgenden Befehl installieren:

npm install -g create-react-app

Sobald du fertig bist, kannst du mit dem nächsten Schritt fortfahren.

Eine React-Beispielanwendung erstellen

In diesem Abschnitt erstellen wir eine React-Beispielanwendung mit dem Create React App Tool.

Wechsle zunächst in das Verzeichnis /opt und erstelle dein erstes Projekt mit dem folgenden Befehl:

cd /opt
create-react-app reactapp

Du solltest die folgende Ausgabe sehen:

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!

Als Nächstes änderst du das Verzeichnis in dein Projektverzeichnis und startest deine Anwendung mit folgendem Befehl:

cd /opt/reactapp
npm start

Du solltest die folgende Ausgabe erhalten:

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

Drücke CTRL+C, um die Anwendung zu stoppen. Wir werden eine systemd-Dienstdatei erstellen, um die React-Anwendung zu verwalten.

Einen Systemd-Dienst für die React-Anwendung erstellen

Als Nächstes musst du einen systemd-Dienst für deine React-Anwendung erstellen. Du kannst ihn mit dem folgenden Befehl erstellen:

nano /lib/systemd/system/react.service

Füge die folgenden Zeilen ein:

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

Speichere und schließe die Datei und lade den systemd-Daemon mit dem folgenden Befehl neu:

systemctl daemon-reload

Als Nächstes startest du den React-Dienst und aktivierst ihn beim Neustart des Systems, indem du den folgenden Befehl ausführst:

systemctl start react
systemctl enable react

Du kannst den Status des React-Dienstes mit dem folgenden Befehl überprüfen:

systemctl status react

Du solltest die folgende Ausgabe erhalten:

? 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

Sobald du fertig bist, kannst du mit dem nächsten Schritt fortfahren.

Nginx als Reverse Proxy konfigurieren

Es ist eine gute Idee, Nginx als Reverse Proxy für die React App zu installieren und zu konfigurieren. So kannst du über Port 80 auf deine App zugreifen.

Installiere zunächst das Nginx-Paket mit dem folgenden Befehl:

apt-get install nginx -y

Sobald Nginx installiert ist, erstellst du eine neue Konfigurationsdatei für den virtuellen Nginx-Host:

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

Füge die folgenden Zeilen hinzu:

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

Speichere und schließe die Datei und aktiviere den virtuellen Nginx-Host mit dem folgenden Befehl:

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

Als Nächstes überprüfst du Nginx auf Syntaxfehler, indem du den folgenden Befehl ausführst:

nginx -t

Du solltest die folgende Ausgabe erhalten:

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

Starte abschließend den Nginx-Dienst neu, um die Änderungen zu übernehmen:

systemctl restart nginx

Du kannst den Status des Nginx-Dienstes auch mit dem folgenden Befehl überprüfen:

systemctl status nginx

Du solltest die folgende Ausgabe sehen:

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

Jetzt ist Nginx installiert und so konfiguriert, dass es die React App bedienen kann. Du kannst jetzt mit dem nächsten Schritt fortfahren.

React.js mit Let’s Encrypt sichern

Als Nächstes musst du das Certbot Client-Paket installieren, um Let’s Encrypt SSL zu installieren und zu verwalten.

Installiere zunächst Certbot mit dem folgenden Befehl:

apt-get install python3-certbot-nginx -y

Sobald die Installation abgeschlossen ist, führst du den folgenden Befehl aus, um Let’s Encrypt SSL auf deiner Website zu installieren:

certbot --nginx -d reactjs.example.com

Du wirst aufgefordert, eine gültige E-Mail-Adresse anzugeben und die Nutzungsbedingungen zu akzeptieren (siehe unten):

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): hitjethva@gmail.com

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

Als Nächstes wählst du aus, ob der HTTP-Datenverkehr auf HTTPS umgeleitet werden soll oder nicht (siehe unten):

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

Gib 2 ein und drücke die Eingabetaste, um die Installation abzuschließen. Du solltest die folgende Ausgabe sehen:

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.

Deine React.js-Webanwendung ist jetzt mit Let’s Encrypt SSL gesichert.

Zugriff auf das React App Web Interface

Öffne jetzt deinen Webbrowser und gib die URL https://reactjs.example.com ein. Auf dem folgenden Bildschirm wirst du zum React.Js-Webinterface weitergeleitet:

Fazit

Glückwunsch! Du hast React.Js erfolgreich auf dem Ubuntu 22.04 Server installiert und konfiguriert. Jetzt kannst du mit der Erstellung deiner eigenen React-basierten Anwendung beginnen und sie in der Produktionsumgebung hosten. Wenn du noch Fragen hast, kannst du dich gerne an mich wenden.

Das könnte dich auch interessieren …