웹사이트 검색

Ubuntu 20.04에 ReactJS를 설치하는 방법


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

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

이 페이지에서

  1. 전제 조건
  2. 시작하기\n
  3. Node.js 설치
  4. Create React App 도구 설치
  5. 첫 번째 React 앱 만들기
  6. React 앱용 시작 파일 만들기
  7. React 앱용 Nginx 구성
  8. React 앱 웹 인터페이스에 액세스
  9. 결론

ReactJS는 재사용 가능한 UI 구성 요소를 구축하는 데 사용되는 무료 오픈 소스 JavaScript 라이브러리입니다. 최소한의 코딩으로 빠르고 효율적으로 풍부하고 매력적인 웹 앱을 만들기 위해 2011년 Facebook에서 개발했습니다. 웹 사이트에서 대화형 요소를 만들 수 있습니다. 앱을 빠르게 만드는 Virtual DOM을 사용합니다. 가상 DOM, 단방향 데이터 바인딩, 구성 요소, JSX, 조건문 등을 비롯한 다양한 기능을 제공합니다.

이 튜토리얼에서는 Ubuntu 20.04에서 Nginx 웹 서버와 함께 create react app을 설치하고 ReactJS 애플리케이션을 호스팅하는 방법을 보여줍니다.

전제 조건

  • 최소 2GB의 RAM이 있는 Ubuntu 20.04를 실행하는 서버.\n
  • 서버 IP를 가리키는 유효한 도메인 이름. 이 튜토리얼에서는 reactjs.example.com 도메인을 사용합니다.\n
  • 루트 암호는 서버에 구성됩니다.\n

시작하기

시작하기 전에 항상 시스템 패키지를 최신 버전으로 업데이트하는 것이 좋습니다. 다음 명령어를 실행하여 업데이트할 수 있습니다.

apt-get update -y

모든 패키지가 업데이트되면 다음 명령어를 실행하여 다른 필수 종속 항목을 설치합니다.

apt-get install curl gnupg2 -y

모든 종속성이 설치되면 다음 단계로 진행할 수 있습니다.

Node.js 설치

다음으로 서버에 Node.js를 설치해야 합니다. 기본적으로 Node.js의 최신 버전은 Ubuntu 20.04 표준 리포지토리에서 사용할 수 없습니다. 따라서 Node.js 공식 저장소에서 Node.js를 설치해야 합니다.

먼저 다음 명령을 사용하여 Node.js 리포지토리를 추가합니다.

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

다음으로 다음 명령을 실행하여 시스템에 Node.js를 설치합니다.

apt-get install nodejs -y

Node.js를 설치한 후 다음 명령을 사용하여 NPM을 최신 버전으로 업데이트합니다.

npm install  -g

다음과 같은 결과가 표시되어야 합니다.

/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
/usr/bin/npx -> /usr/lib/node_modules/npm/bin/npx-cli.js
+ 
updated 2 packages in 12.78s

다음으로 다음 명령을 사용하여 설치된 Node.js 버전을 확인합니다.

node -v

다음과 같은 결과가 표시되어야 합니다.

v14.15.3

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

Create React App 도구 설치

Create React App은 설정 및 구성 시간을 절약해주는 도구입니다. 단일 명령을 실행하기만 하면 Create React App이 프로젝트를 시작하는 데 필요한 모든 도구를 설정합니다.

다음 명령을 사용하여 Create React App 도구를 설치할 수 있습니다.

npm install -g create-react-app

다음과 같은 결과가 표시되어야 합니다.

/usr/bin/create-react-app -> /usr/lib/node_modules/create-react-app/index.js
+ 
added 67 packages from 25 contributors in 4.705s

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

첫 번째 React 앱 만들기

이 섹션에서는 Create React App 도구를 사용하여 React 앱을 만드는 방법을 보여줍니다.

먼저 디렉터리를 /opt로 변경하고 다음 명령을 사용하여 첫 번째 프로젝트를 만듭니다.

cd /opt
create-react-app reactproject

다음 출력이 표시되어야 합니다.

Success! Created reactproject at /opt/reactproject
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 reactproject
  npm start

Happy hacking!

다음으로 디렉터리를 프로젝트로 변경하고 다음 명령을 사용하여 애플리케이션을 시작합니다.

cd /opt/reactproject
npm start

다음과 같은 결과가 표시되어야 합니다.

Compiled successfully!

You can now view reactproject in the browser.

  http://localhost:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

Ctrl+C를 눌러 응용 프로그램을 중지합니다.

React 앱용 시작 파일 생성

시스템 재부팅 시 React 앱을 자동으로 시작하려면 React 앱에 대한 systemd 서비스를 생성해야 합니다. 따라서 systemctl 명령을 사용하여 앱을 쉽게 관리할 수 있습니다. 다음 명령을 사용하여 systemd 서비스 파일을 만들 수 있습니다.

nano /lib/systemd/system/react.service

다음 줄을 추가합니다.

[Service]
Type=simple
User=root
Restart=on-failure
WorkingDirectory=/opt/reactproject
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; vendor preset: enabled)
     Active: active (running) since Sat 2020-12-19 06:11:42 UTC; 4s ago
   Main PID: 30833 (node)
      Tasks: 30 (limit: 4691)
     Memory: 141.0M
     CGroup: /system.slice/react.service
             ??30833 npm
             ??30844 sh -c react-scripts start "--port=3000"
             ??30845 node /opt/reactproject/node_modules/.bin/react-scripts start --port=3000
             ??30852 /usr/bin/node /opt/reactproject/node_modules/react-scripts/scripts/start.js --port=3000

Dec 19 06:11:42 ubunt4 systemd[1]: Started react.service.
Dec 19 06:11:43 ubunt4 npm[30833]: >  start /opt/reactproject
Dec 19 06:11:43 ubunt4 npm[30833]: > react-scripts start "--port=3000"
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: Project is running at http://0.0.0.0:3000/
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: webpack output is served from
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: Content not from webpack is served from /opt/reactproject/public
Dec 19 06:11:46 ubunt4 npm[30852]: ? ?wds?: 404s will fallback to /
Dec 19 06:11:46 ubunt4 npm[30852]: Starting the development server...

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

React 앱용 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 Sat 2020-12-19 06:12:42 UTC; 4s ago
       Docs: man:nginx(8)
    Process: 30899 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 30913 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 30915 (nginx)
      Tasks: 3 (limit: 4691)
     Memory: 3.6M
     CGroup: /system.slice/nginx.service
             ??30915 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             ??30916 nginx: worker process
             ??30917 nginx: worker process

Dec 19 06:12:42 ubunt4 systemd[1]: Starting A high performance web server and a reverse proxy server...
Dec 19 06:12:42 ubunt4 systemd[1]: Started A high performance web server and a reverse proxy server.

이 시점에서 Nginx가 설치되고 React 앱을 제공하도록 구성됩니다. 이제 다음 단계를 진행할 수 있습니다.

React 앱 웹 인터페이스에 액세스

이제 웹 브라우저를 열고 URL http://reactjs.example.com을 입력합니다. 다음 화면에서 React.Js 웹 인터페이스로 리디렉션됩니다.

결론

축하합니다! Ubuntu 20.04 서버에 React.Js를 성공적으로 설치하고 구성했습니다. 프로덕션 환경에서 자체 React 애플리케이션을 배포할 수 있는 충분한 지식을 갖추셨기를 바랍니다. 궁금한 점이 있으면 언제든지 문의해 주세요.