웹사이트 검색

Ubuntu 22.04에서 Nginx와 함께 ReactJS를 설치하는 방법


이 튜토리얼은 다음 OS 버전에 대해 존재합니다.

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

이 페이지에서

  1. 전제 조건
  2. 시작하기\n
  3. Node.js 설치
  4. Create React App 도구 설치
  5. 샘플 React 애플리케이션 만들기\n
  6. React 앱을 위한 Systemd 서비스 만들기\n
  7. Nginx를 역방향 프록시로 구성\n
  8. Lets Encrypt로 React.js 보호\n
  9. React 앱 웹 인터페이스에 액세스
  10. 결론

React.js는 2011년 Facebook에서 개발한 무료 오픈 소스 JavaScript 프레임워크입니다. 재사용 가능한 UI 구성요소를 구축하는 데 사용되며 사용자가 최소한의 코딩으로 빠르고 효율적으로 풍부하고 매력적인 웹 앱을 만들 수 있도록 도와줍니다. React를 사용하면 대화형 웹 인터페이스를 구축하고 작고 고립된 부분에서 복잡한 UI를 구성할 수 있습니다. 앱을 빠르게 만드는 Virtual DOM을 사용합니다. 가상 DOM, 단방향 데이터 바인딩, 구성 요소, JSX, 조건문 등과 같은 많은 기능을 제공합니다.

이 튜토리얼에서는 Ubuntu 22.04에 React.js를 설치하는 방법을 보여줍니다.

전제 조건

  • Ubuntu 22.04를 실행하는 서버.\n
  • 서버 IP를 가리키는 유효한 도메인 이름입니다.\n
  • 루트 암호는 서버에서 구성됩니다.\n

시작하기

먼저 시스템 패키지를 최신 버전으로 업데이트해야 합니다. 다음 명령을 사용하여 업데이트할 수 있습니다.

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

완료되면 다음 단계로 진행할 수 있습니다.

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를 눌러 응용 프로그램을 중지합니다. React 애플리케이션을 관리하기 위해 systemd 서비스 파일을 생성합니다.

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를 역방향 프록시로 구성

React App의 리버스 프록시로 Nginx를 설치하고 구성하는 것이 좋습니다. 따라서 포트 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 앱을 제공하도록 구성됩니다. 이제 다음 단계로 진행할 수 있습니다.

Lets Encrypt로 React.js 보호

다음으로 Lets Encrypt SSL을 설치하고 관리하려면 Certbot 클라이언트 패키지를 설치해야 합니다.

먼저 다음 명령을 사용하여 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 웹 인터페이스로 리디렉션됩니다.

결론

축하합니다! Ubuntu 22.04 서버에 React.Js를 성공적으로 설치하고 구성했습니다. 이제 자체 React 기반 애플리케이션 구축을 시작하고 프로덕션 환경에서 호스팅할 수 있습니다. 궁금한 점이 있으면 언제든지 문의해 주세요.