EKS 클러스터에 프런트앤드 어플리케이션 배포하기

2021-08-16

.

Data_Engineering_TIL(20210816)

[학습자료]

“클라우드 네이티브를 위한 쿠버네티스 실전 프로젝트” 책을 읽고 실습한 내용입니다.

** 동양북스, 아이자와 고지&사토 가즈히코 지음, 박상욱 옮김

참고자료 URL : https://github.com/dybooksIT/k8s-aws-book

[학습내용]

“EKS 클러스터에 API 어플리케이션 배포하기”에 이어서 진행을 한 실습을 진행한 내용임

** URL : https://minman2115.github.io/DE_TIL253

  • 실습의 최종 목표

서비스의 최종 구현 목표

architecture3

아키텍처 관점에서 최종목표

architecture2

  • 오늘의 실습목표

프론트앤드 어플리케이션을 빌드하고 EKS 클러스터에 배포한다.

  • 실습내용

먼저 ec2 베스천에서 아래와 같이 node js를 설치한다.

[ec2-user@ip-10-0-1-252 frontend-app]$ cd ~

[ec2-user@ip-10-0-1-252 ~]$ pwd
/home/ec2-user

[ec2-user@ip-10-0-1-252 ~]$ cd k8s-aws-book/frontend-app

# node js 설치하기
# 참고자료 : https://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v2/developer-guide/setting-up-node-on-ec2-instance.html 
[ec2-user@ip-10-0-1-252 frontend-app]$ npm
-bash: npm: command not found

[ec2-user@ip-10-0-1-252 frontend-app]$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 13226  100 13226    0     0  34623      0 --:--:-- --:--:-- --:--:-- 34713
=> Downloading nvm from git to '/home/ec2-user/.nvm'
=> Cloning into '/home/ec2-user/.nvm'...
remote: Enumerating objects: 278, done.
remote: Counting objects: 100% (278/278), done.
remote: Compressing objects: 100% (245/245), done.
remote: Total 278 (delta 31), reused 101 (delta 20), pack-reused 0
Receiving objects: 100% (278/278), 142.25 KiB | 7.49 MiB/s, done.
Resolving deltas: 100% (31/31), done.
=> Compressing and cleaning up git repository

=> Appending nvm source string to /home/ec2-user/.bashrc
=> Appending bash_completion source string to /home/ec2-user/.bashrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

[ec2-user@ip-10-0-1-252 frontend-app]$ . ~/.nvm/nvm.sh

# 버전 중요함 node 버전 15.14.0 설치필요
[ec2-user@ip-10-0-1-252 frontend-app]$ nvm install 15.14.0

[ec2-user@ip-10-0-1-252 frontend-app]$ node -e "console.log('Running Node.js ' + process.version)"
Running Node.js v15.14.0

[ec2-user@ip-10-0-1-252 frontend-app]$ npm -v
7.7.6

[ec2-user@ip-10-0-1-252 frontend-app]$ ll
total 1460
drwxrwxr-x 3 ec2-user ec2-user      19 Aug 13 12:28 assets
-rw-rw-r-- 1 ec2-user ec2-user     409 Aug 13 12:28 jest.config.js
drwxrwxr-x 2 ec2-user ec2-user      42 Aug 13 12:28 layouts
drwxrwxr-x 2 ec2-user ec2-user      22 Aug 13 12:28 middleware
-rw-rw-r-- 1 ec2-user ec2-user    1855 Aug 13 12:28 nuxt.config.js
-rw-rw-r-- 1 ec2-user ec2-user     711 Aug 13 12:28 package.json
-rw-rw-r-- 1 ec2-user ec2-user 1479517 Aug 13 12:28 package-lock.json
drwxrwxr-x 2 ec2-user ec2-user      47 Aug 13 12:28 pages
drwxrwxr-x 2 ec2-user ec2-user      22 Aug 13 12:28 plugins
drwxrwxr-x 2 ec2-user ec2-user      38 Aug 13 12:28 static
drwxrwxr-x 2 ec2-user ec2-user      22 Aug 13 12:28 store
drwxrwxr-x 2 ec2-user ec2-user      22 Aug 13 12:28 test

[ec2-user@ip-10-0-1-252 frontend-app]$ sudo yum install gcc-c++ -y

그런 다음에 프런트앤드 어플리케이션을 아래와 같이 빌드한다.

[ec2-user@ip-10-0-1-252 ~]$ cd k8s-aws-book/frontend-app

# 라이브러리 다운로드
[ec2-user@ip-10-0-1-252 frontend-app]$ npm install

# API 기본 URL 확인
# kubectl get all 명령어를 날렸을때 ELB 주소인 xxxxxxxx.ap-northeast-2.elb.amazonaws.com를 체크해놓는다.
[ec2-user@ip-10-0-1-252 frontend-app]$ kubectl get all

# 빌드실행
# 위에서 체크한 API 기본 URL를 BASE_URL로 잡아서 실행하면 된다.
# 혹시 아래와 같이 명령어를 실행했는데 
# Error: Cannot find module '/home/ec2-user/k8s-aws-book/frontend-app/node_modules/fibers/bin/linux-x64-88-glibc/fibers'
# 이런에러가 발생하면
# npm install fibers 명령어로 fibers를 설치하고 다시 실행하면 될것이다.
# 그래도 안되면 아래의 명령어를 차례대로 실행하고 다시 해본다.
# npm clean-install
# npm install
# npm run build
[ec2-user@ip-10-0-1-252 frontend-app]$ BASE_URL=http://xxxxxxxx.ap-northeast-2.elb.amazonaws.com:8080 npm run build

> frontend-app@1.0.0 build
> nuxt build


 WARN  sass-loader@8.0.2 is installed but ^10.1.1 is expected                                                                             16:37:49


 WARN  mode option is deprecated. Please use ssr: true for universal mode or ssr: false for spa mode and remove mode from nuxt.config     16:37:49

ℹ Production build                                                                                                                       16:37:51
ℹ Bundling only for client side                                                                                                          16:37:51
ℹ Target: static                                                                                                                         16:37:51
✔ Builder initialized                                                                                                                    16:37:51
✔ Nuxt files generated                                                                                                                   16:37:51

✔ Client
  Compiled successfully in 15.41s


Hash: xxxxxxxxxxxxxxxxxx
Version: webpack 4.46.0
Time: 15411ms
Built at: 08/15/2021 4:38:07 PM
                         Asset       Size  Chunks                                Chunk Names
../server/client.manifest.json   10.3 KiB          [emitted]
                    xxxxxxxx.js   1.96 KiB       2  [emitted] [immutable]         pages/index
                    xxxxxxxxx.js     45 KiB       0  [emitted] [immutable]         app
                    xxxxxxx.js    280 KiB       5  [emitted] [immutable]  [big]  vendors/app
                      LICENSES  451 bytes          [emitted]
                    xxxxxxx.js   2.09 KiB       3  [emitted] [immutable]         pages/regionDetail
                    xxxxxxx.js    198 KiB       1  [emitted] [immutable]         commons/app
                    xxxxxx.js    2.3 KiB       4  [emitted] [immutable]         runtime
 + 1 hidden asset
Entrypoint app = xxxxxxxx.js xxxxxxxxxx.js xxxxxxxxxxxx.js xxxxxxxxxxx.js

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  7c7edf5.js (280 KiB)
ℹ Generating output directory: dist/                                                     16:38:07
ℹ Generating pages                                                                       16:38:07
✔ Generated route "/regionDetail"                                                        16:38:07
✔ Generated route "/"                                                                    16:38:07
✔ Client-side fallback created: 200.html                                                 16:38:07

아래와 같이 S3 버킷과 cloud front 배포를 생성한다.

먼저 클라우드 포메이션에서 yaml 파일을 실행할건데 내용을 확인해본다.

[ec2-user@ip-10-10-1-181 frontend-app]$ cd /home/ec2-user/k8s-aws-book/eks-env

[ec2-user@ip-10-10-1-181 eks-env]$ ll
total 60
-rw-rw-r-- 1 ec2-user ec2-user 3135 Aug 14 07:53 01_base_resources_cfn.yaml
-rw-rw-r-- 1 ec2-user ec2-user  180 Aug 14 07:53 02_nginx_k8s.yaml
-rw-rw-r-- 1 ec2-user ec2-user 7924 Aug 14 07:53 10_rds_ope_cfn_mysql.yaml
-rw-rw-r-- 1 ec2-user ec2-user 7957 Aug 14 07:53 10_rds_ope_cfn.yaml
-rw-rw-r-- 1 ec2-user ec2-user   58 Aug 14 07:53 20_create_namespace_k8s.yaml
-rw-rw-r-- 1 ec2-user ec2-user  153 Aug 14 07:53 21_db_config_k8s.yaml.template
-rw-rw-r-- 1 ec2-user ec2-user 1397 Aug 14 07:53 22_deployment_backend-app_k8s.yaml.template
-rw-rw-r-- 1 ec2-user ec2-user  190 Aug 14 07:53 23_service_backend-app_k8s.yaml
-rw-rw-r-- 1 ec2-user ec2-user 1253 Aug 14 07:53 30_s3_cloudfront_cfn.yaml
-rw-rw-r-- 1 ec2-user ec2-user 1677 Aug 14 07:53 40_s3_batch_cfn.yaml
-rw-rw-r-- 1 ec2-user ec2-user  195 Aug 14 07:53 41_config_map_batch_k8s.yaml.template
-rw-rw-r-- 1 ec2-user ec2-user  158 Aug 14 07:53 42_batch_secrets_k8s.yaml.template
-rw-rw-r-- 1 ec2-user ec2-user 1939 Aug 14 07:53 43_cronjob_k8s.yaml.template
drwxrwxr-x 2 ec2-user ec2-user  154 Aug 14 07:53 cloudwatch-yaml

[ec2-user@ip-10-10-1-181 eks-env]$ cat 30_s3_cloudfront_cfn.yaml
AWSTemplateFormatVersion: '2010-09-09'

Parameters:
  TargetRegion:
    Type: String
    Default: ap-northeast-2

  BucketBaseName:
    Type: String
    Default: eks-work-frontend-

  BucketSuffix:
    Type: String

Resources:
  ContentsBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Join ["", [!Ref BucketBaseName, !Ref BucketSuffix]]
      AccessControl: Private
      PublicAccessBlockConfiguration:
        BlockPublicAcls: false
        BlockPublicPolicy: false
        IgnorePublicAcls: false
        RestrictPublicBuckets: false

  ContentsDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Origins:
        - Id: S3Origin
          DomainName: !GetAtt ContentsBucket.DomainName
          CustomOriginConfig:
            OriginProtocolPolicy: match-viewer
        Enabled: true
        DefaultRootObject: index.html
        Comment: !Ref AWS::StackName
        DefaultCacheBehavior:
          TargetOriginId: S3Origin
          ForwardedValues:
            QueryString: false
          ViewerProtocolPolicy: allow-all

Outputs:
  URL:
    Value: !Join ["", ["http://", !GetAtt [ContentsDistribution, DomainName] ]]

  DistributionID:
    Value: !Ref ContentsDistribution

그런 다음에 클라우드 포메이션으로 해당 yaml파일을 아래와 같이 실행해준다.

1

그런 다음에 아래와 같이 빌드한 프런트앤드 어플리케이션(dist 폴더) 컨텐츠를 s3에 저장하고 업데이트 한다.

[ec2-user@ip-10-10-1-181 frontend-app]$ cd /home/ec2-user/k8s-aws-book/frontend-app

[ec2-user@ip-10-10-1-181 frontend-app]$ ll
total 1176
drwxrwxr-x   3 ec2-user ec2-user      19 Aug 14 07:53 assets
drwxrwxr-x   4 ec2-user ec2-user     122 Aug 15 16:38 dist
-rw-rw-r--   1 ec2-user ec2-user     409 Aug 14 07:53 jest.config.js
drwxrwxr-x   2 ec2-user ec2-user      42 Aug 14 07:53 layouts
drwxrwxr-x   2 ec2-user ec2-user      22 Aug 14 07:53 middleware
drwxrwxr-x 990 ec2-user ec2-user   28672 Aug 15 16:37 node_modules
-rw-rw-r--   1 ec2-user ec2-user    1855 Aug 14 07:53 nuxt.config.js
-rw-rw-r--   1 ec2-user ec2-user     711 Aug 14 07:53 package.json
-rw-rw-r--   1 ec2-user ec2-user 1139734 Aug 15 16:37 package-lock.json
drwxrwxr-x   2 ec2-user ec2-user      47 Aug 14 07:53 pages
drwxrwxr-x   2 ec2-user ec2-user      22 Aug 14 07:53 plugins
drwxrwxr-x   2 ec2-user ec2-user      38 Aug 14 07:53 static
drwxrwxr-x   2 ec2-user ec2-user      22 Aug 14 07:53 store
drwxrwxr-x   2 ec2-user ec2-user      22 Aug 14 07:53 test

[ec2-user@ip-10-10-1-181 frontend-app]$ aws s3 sync dist s3://eks-work-frontend-xxx --delete --include "*" --acl public-read
upload: dist/.nojekyll to s3://eks-work-frontend-xxx/.nojekyll
upload: dist/_nuxt/e77af6f.js to s3://eks-work-frontend-xxx/_nuxt/e77af6f.js
upload: dist/_nuxt/LICENSES to s3://eks-work-frontend-xxx/_nuxt/LICENSES
upload: dist/_nuxt/76aaced.js to s3://eks-work-frontend-xxx/_nuxt/76aaced.js
upload: dist/200.html to s3://eks-work-frontend-xxx/200.html
upload: dist/regionDetail/index.html to s3://eks-work-frontend-xxx/regionDetail/index.html
upload: dist/_nuxt/aeac852.js to s3://eks-work-frontend-xxx/_nuxt/aeac852.js
upload: dist/index.html to s3://eks-work-frontend-xxx/index.html
upload: dist/v.png to s3://eks-work-frontend-xxx/v.png
upload: dist/_nuxt/770fe45.js to s3://eks-work-frontend-xxx/_nuxt/770fe45.js
upload: dist/favicon.ico to s3://eks-work-frontend-pms/favicon.ico
upload: dist/_nuxt/7c7edf5.js to s3://eks-work-frontend-xxx/_nuxt/7c7edf5.js
upload: dist/_nuxt/d8c27c2.js to s3://eks-work-frontend-xxx/_nuxt/d8c27c2.js

# distribuion id 는 위에 그림과 같이 클라우드 포메이션을 실행한후의 output 메뉴에서 확인이 가능하다.
[ec2-user@ip-10-10-1-181 frontend-app]$ aws cloudfront create-invalidation --distribution-id xxxxxxxxxxxxxx --paths "/*"
{
    "Invalidation": {
        "Status": "InProgress",
        "InvalidationBatch": {
            "Paths": {
                "Items": [
                    "/*"
                ],
                "Quantity": 1
            },
            "CallerReference": "cli-xxxxxxxx-xxxxxxxxxxx"
        },
        "Id": "xxxxxxxxxxxxxxxx",
        "CreateTime": "2021-08-15T17:08:11.178Z"
    },
    "Location": "https://cloudfront.amazonaws.com/2020-05-31/distribution/xxxxxxxxxxxxxx/invalidation/yyyyyyyyyyyy"
}

클라우드 포메이션을 통해서 어플리케이션 동작 확인

어플리케이션 URL은 위에 그림과 같이 클라우드 포메이션을 실행한후의 output 메뉴에서 확인이 가능하다.

그 URL로 접속하면 되는데 404 not found가 표시될 경우에 Home page 링크를 클릭할 경우 아래 그림과 같이 어플리케이션이 전시될 것이다.

2