웹사이트 검색

Ubuntu 22.04에 MEAN 스택을 설치하는 방법


이 페이지에서

  1. 전제 조건
  2. 시작하기\n
  3. MongoDB 설치
  4. Node.js 설치
  5. MEAN 스택 다운로드 및 설치
  6. MEAN 애플리케이션 만들기\n
  7. MEAN 애플리케이션용 Nginx 설치 및 구성\n
  8. MEAN 애플리케이션 액세스\n
  9. 결론

MEAN 스택은 웹 애플리케이션 개발에 사용되는 무료 오픈 소스 JavaScript 기반 프레임워크입니다. MEAN은 MongoDB, Express, Angular 및 Node의 네 가지 핵심 기술로 만들어집니다. 이 스택은 JavaScript로 웹 애플리케이션을 구축하고 JSON을 매우 쉽게 처리할 수 있도록 설계되었습니다. 다양한 방법으로 MEAN 애플리케이션을 사용할 수 있습니다. 그러나 특히 실시간 애플리케이션, 특히 클라우드에서 기본적으로 실행되는 애플리케이션과 Angular.js로 구축된 단일 페이지(동적) 웹 애플리케이션에 적합합니다.

이 게시물에서는 Ubuntu 22.04 서버에 MEAN 스택을 설치하는 방법을 보여줍니다.

전제 조건

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

시작하기

시작하기 전에 모든 시스템 패키지를 최신 버전으로 업데이트하는 것이 좋습니다. 다음 명령으로 모두 업데이트할 수 있습니다.

apt update -y
apt upgrade -y

모든 패키지가 업데이트되면 다음 명령을 사용하여 필요한 종속성을 설치합니다.

apt install python3 dirmngr gnupg apt-transport-https ca-certificates software-properties-common -y

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

몽고DB 설치

기본적으로 MongoDB 패키지는 Ubuntu 기본 리포지토리에 포함되어 있지 않습니다. 따라서 서버에 MongoDB 리포지토리를 추가해야 합니다.

먼저 다음 명령을 사용하여 MongoDB 키를 다운로드하고 추가합니다.

wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | apt-key add -

다음으로 다음 명령을 사용하여 APT에 MongoDB 리포지토리를 추가합니다.

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-4.4.list

다음으로 다음 명령을 사용하여 libssl 종속성을 다운로드하고 설치합니다.

wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb
dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.deb

그런 다음 리포지토리를 업데이트하고 다음 명령을 사용하여 MongoDB 패키지를 설치합니다.

apt-get update -y
apt-get install mongodb-org -y

성공적으로 설치한 후 다음 명령을 사용하여 MongoDB 서비스를 시작하고 활성화합니다.

systemctl start mongod
systemctl enable mongod

그런 다음 다음 명령을 사용하여 MongoDB 서비스의 상태를 확인합니다.

systemctl status mongod

다음과 같은 결과가 표시됩니다.

? mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-10-30 07:30:10 UTC; 5s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 2995 (mongod)
     Memory: 60.5M
        CPU: 1.050s
     CGroup: /system.slice/mongod.service
             ??2995 /usr/bin/mongod --config /etc/mongod.conf

Oct 30 07:30:10 ubuntu2204 systemd[1]: Started MongoDB Database Server.

완료되면 Node.js 설치를 진행할 수 있습니다.

Node.js 설치

기본적으로 Node.js 패키지는 Ubuntu 기본 리포지토리에 포함되어 있지 않습니다. 따라서 Node 소스 리포지토리에서 설치해야 합니다.

먼저 다음 명령을 사용하여 노드 소스 리포지토리를 추가합니다.

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

다음으로 다음 명령을 사용하여 Node.js 패키지를 설치합니다.

apt-get install nodejs -y

Node.js 패키지가 설치되면 다음 명령을 사용하여 Node.js 버전을 확인할 수 있습니다.

node -v

다음과 같은 결과가 표시됩니다.

v18.12.0

다음으로 NPM을 사용하여 Yarn, Gulp 및 PM2 패키지를 설치합니다.

npm install -g yarn
npm install -g gulp
npm install pm2 -g

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

MEAN 스택 다운로드 및 설치

먼저 Git 리포지토리에서 최신 버전의 MEAN 스택을 다운로드해야 합니다. 다음 명령을 사용하여 다운로드할 수 있습니다.

git clone https://github.com/meanjs/mean

다운로드가 완료되면 다운로드한 디렉터리로 이동하고 다음 명령을 사용하여 필요한 모든 종속성을 설치합니다.

cd mean
yarn install

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

MEAN 애플리케이션 만들기

이 섹션에서는 간단한 MEAN 애플리케이션을 생성합니다.

이렇게 하려면 다음 명령을 사용하여 mean 디렉토리 내에 MEAN 애플리케이션을 만듭니다.

nano server.js

다음 코드를 추가합니다.

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();

app.use('/', (req, res) => {
MongoClient.connect("mongodb://localhost:27017/test", function(err, db){
db.collection('Example', function(err, collection){
collection.insert({ pageHits: 'pageHits' });
db.collection('Example').count(function(err, count){
if(err) throw err;
res.status(200).send('Page Hits: ' + Math.floor(count/2));
});
});
});
});

app.listen(3000);
console.log('Server running at http://localhost:3000/');

module.exports = app;

파일을 저장하고 닫은 다음 PM2를 사용하여 애플리케이션을 시작합니다.

pm2 start server.js

다음과 같은 결과가 표시됩니다.

                          Runtime Edition

        PM2 is a Production Process Manager for Node.js applications
                     with a built-in Load Balancer.

                Start and Daemonize any application:
                $ pm2 start app.js

                Load Balance 4 instances of api.js:
                $ pm2 start api.js -i 4

                Monitor in production:
                $ pm2 monitor

                Make pm2 auto-boot at server restart:
                $ pm2 startup

                To go further checkout:
                http://pm2.io/


                        -------------

[PM2] Spawning PM2 daemon with pm2_home=/root/.pm2
[PM2] PM2 Successfully daemonized
[PM2] Starting /root/mean/server.js in fork_mode (1 instance)
[PM2] Done.
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
? id  ? name      ? namespace   ? version ? mode    ? pid      ? uptime ? ?    ? status    ? cpu      ? mem      ? user     ? watching ?
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
? 0   ? server    ? default     ? 0.6.0   ? fork    ? 5644     ? 0s     ? 0    ? online    ? 0%       ? 45.2mb   ? root     ? disabled ?
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

다음으로 MEAN 애플리케이션이 시스템 재부팅 후 시작되도록 활성화합니다.

pm2 startup

다음과 같은 결과가 표시됩니다.

Target path
/etc/systemd/system/pm2-root.service
Command list
[ 'systemctl enable pm2-root' ]
[PM2] Writing init configuration in /etc/systemd/system/pm2-root.service
[PM2] Making script booting at startup...
[PM2] [-] Executing: systemctl enable pm2-root...
Created symlink /etc/systemd/system/multi-user.target.wants/pm2-root.service → /etc/systemd/system/pm2-root.service.
[PM2] [v] Command successfully executed.
+---------------------------------------+
[PM2] Freeze a process list on reboot via:
$ pm2 save

[PM2] Remove init script via:
$ pm2 unstartup systemd

기본적으로 MEAN 애플리케이션은 포트 3000에서 수신 대기합니다. 다음 명령으로 확인할 수 있습니다.

ss -antpl | grep 3000

다음과 같은 결과가 표시됩니다.

LISTEN 0      511                *:3000             *:*    users:(("node /root/mean",pid=5644,fd=20))

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

MEAN 애플리케이션용 Nginx 설치 및 구성

먼저 다음 명령을 사용하여 Nginx 웹 서버 패키지를 설치합니다.

apt-get install nginx -y

Nginx가 설치되면 다음 명령을 사용하여 Nginx 가상 호스트 구성 파일을 만듭니다.

nano /etc/nginx/conf.d/mean.conf

다음 구성을 추가합니다.

server {
listen 80;

server_name mean.example.com;
access_log /var/log/nginx/mean-access.log;
error_log /var/log/nginx/mean-error.log;

location / {
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:3000/;
}
}

파일을 저장하고 닫은 후 다음 명령을 사용하여 구문 오류가 있는지 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-10-30 07:37:24 UTC; 4s ago
       Docs: man:nginx(8)
    Process: 6416 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 6417 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 6418 (nginx)
      Tasks: 3 (limit: 4579)
     Memory: 3.3M
        CPU: 49ms
     CGroup: /system.slice/nginx.service
             ??6418 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             ??6419 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
             ??6420 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""

Oct 30 07:37:24 ubuntu2204 systemd[1]: Starting A high performance web server and a reverse proxy server...
Oct 30 07:37:24 ubuntu2204 systemd[1]: Started A high performance web server and a reverse proxy server.

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

액세스 MEAN 애플리케이션

이 시점에서 Nginx는 MEAN 애플리케이션의 리버스 프록시로 설치 및 구성됩니다. 이제 URL http://mean.example.com을 사용하여 MEAN 애플리케이션에 액세스할 수 있습니다. 다음 화면에 MEAN 웹 인터페이스가 표시되어야 합니다.

결론

축하합니다! Ubuntu 22.04에서 MEAN 스택을 성공적으로 설치하고 구성했습니다. 이제 MEAN 스택을 사용하여 애플리케이션 개발을 시작하고 프로덕션 서버에서 호스팅할 수 있습니다. 궁금한 점이 있으면 언제든지 문의해 주세요.