Github를 이용한 CI/CD 구축

dongwon·2021년 3월 5일
0
post-thumbnail

Github Actions / Pages를 이용한 CI/CD 설정

Github를 이용해 React로 만든 웹 프로젝트 CI/CD 설정했던 과정을 정리한 글입니다.
틀린 내용이 있을 수 있습니다.


CI / CD란?

CI : 통합적 지속

Build, Test를 실시하는 프로세스. 이러한 프로세스를 상시로 실시해 주는 것.

CD : 지속적 배포

짧은 주기로 개발중인 소프트웨어를 배포하고 자동화 하는 것.


Gitgub Actions을 이용한 CI 설정

1. 배포하고자 하는 레파지토리의 workflow 설정

  • Actions -> Set up this workflow
    set workflow

  • build.yml로 파일명 변경 -> commit
    create build yml


2. 레파지토리 .gitgub\workflows의 build.yml에 Workflow 작성

  • Workflow 작성 참고

  • Workflow 구조

    1. master branch(개발용)에서 push 했을 때 Workflow 실행
    2. build 하기 위환 환경 설정 (node, npm, 상대경로)
    3. github page 사용하기 위한 폴더 이름 변경
    4. 배포용 브랜치 release에 변경사항 적용
  • build.yml

    name: CI
    on:
    push:
        ##### 1 #####
        branches: [master]
    
        workflow_dispatch:
    
    jobs:
    build:
        runs-on: ubuntu-latest
        steps:
        ##### 2 #####
        # 레파지토리 check out
        - name: Checkout source code.
            uses: actions/checkout@v2
    
        # node.js 버전 12
        - uses: actions/setup-node@v2
            with:
            node-version: '12'
    
        # npm 설치
        - name: Install Dependencies
            run: npm install
    
        #환경변수 설정 ( 상대경로 지정 )
        - name: Set Env
            run: echo "PUBLIC_URL=/${GITHUB_REPOSITORY#*/}" >> $GITHUB_ENV
    
        # 빌드
        - name: Build
            run: npm run build
    
        ##### 3 #####
        # 폴더 이름 변경
        - name: Change folder name build to docs
            run: mv build docs
    
        ##### 4 #####
        # git 인증
        - uses: actions/labeler@v2
            with:
            repo-token: ${{ secrets.GITHUB_TOKEN }}
    
        # git remote update
        - name: Remote Update
            run: git remote update
    
        # git fetch
        - name: Fetch
            run: git fetch --all
    
        # stash 생성
        - name: Stash
            run: git stash
    
        # 배포용 release 생성 후 이동
        - name: create release branch
            run: git checkout -b release
    
        # stash 적용
        - name: Apply stash
            run: git stash pop
    
        # 사용자 인증
        - name: Github auth and commit
            env:
            MY_EMAIL: [사용자 이메일]
            MY_NAME: [사용자 이름]
            run: |
            git config --global user.email $MY_EMAIL
            git config --global user.name $MY_NAME
    
        # releaes 브랜치에 push
        - name: git commit
            run: |
            git add .
            git commit -m "Build done!"
            git push -f --set-upstream origin release

3. 테스트하기

  • master branch에서 변경 사항 push

  • 레파지토리 Actions 탭 -> workflow 클릭
    action state

  • 진행 완료
    테스트 성공

  • release branch의 docs 폴더 생성 확인

    check docs


Gitgub Pages을 이용한 CD 설정

Github Pages를 이용해 build 후 생성되는 정적 파일 배포

1. 레파지토리 Github pages 설정

  • Settings탭 -> GitHub Pages -> release branch 선택 -> /docs 폴더 선택
    github page setting

2. build로 생성된 정적 파일 경로 설정

  • 제공되어진 url로 이동하면 흰 페이지에 오류 목록이 나옵니다.
    path error

  • 원인 분석

    • 이 오류는 css나 jpg가 올바르지 않은 경로로 load 되었기 때문에 발생하는 오류입니다.

    • Github pages를 이용하면 기본 url로 github.com/[깃허브 ID]/[레파지토리 name]가 주어집니다.

    • 이 때 build로 생성된 index.html에서는 파일들을 github.com/[깃허브 ID]/static... 로 부터 파일들을 로드하기 때문에 github.com/[깃허브 ID]/[레파지토리 name]/static... 으로 변환하는 과정이 필요합니다.

      css load

  • 원인 해결

    개발(start), 배포(build) 시 둘다 자동화되도록 설정했습니다.

    1. config -> paths.js의 publicUrlOrPath의 주석을 보면 homepage를 통해 path를 설정하는 것을 알 수 있습니다.

          // We use `PUBLIC_URL` environment variable or "homepage" field to infer
          // "public path" at which the app is served.
          // webpack needs to know it to put the right <script> hrefs into HTML even in
          // single-page apps that may serve index.html for nested URLs like /todos/42.
          // We can't use a relative path in HTML because we don't want to load something
          // like /todos/42/static/js/bundle.7289d.js. We have to know the root.
      
          const publicUrlOrPath = getPublicUrlOrPath(
          process.env.NODE_ENV === 'development',
          require(resolveApp('package.json')).homepage,
          process.env.PUBLIC_URL,
          );
    2. require(resolveApp('package.json')).homepage : package.json 객체의 homepage값을 참조해라.
      package.json 파일의 마지막에 homepage를 추가해서 경로를 지정할 수 있습니다.

      ...
          ]
      },
      homepage : "레파지토리 name"
    3. 위 방법은 배포용일 때만 해당, 개발용을 위해서는 다시 고쳐야하는 불필요한 작업이 필요합니다.
      -> 개발용, 배포용 자동화 과정 필요. confing - paths.js에서 코드 수정

      const homepage =
      process.env.NODE_ENV === 'development'
      ? '/'
      : require(resolveApp('package.json')).homepage;
      
      const publicUrlOrPath = getPublicUrlOrPath(
         process.env.NODE_ENV === 'development',
         homepage,
         process.env.PUBLIC_URL,
      );
    • 코드 해석
      1. script folder의 start.js (개발용), build.js(배포용)을 보면 각각 process.env.NODE_ENV값이 'development', 'production'인 것을 알 수 있습니다.
      2. publicUrlOrPath의 2번째 인자는 결국 문자열입니다. (package.json 객체의 homepage 문자열 값)
      3. 개발용일 때 process.env.NODE_ENV === 'development'일 때 '/' 경로 설정, 그 외엔 homepage 문자열 값으로 경로 설정

3. React Router basename 설정

  • 마찬가지로 Github pages를 이용하면 기본 url로 github.com/[깃허브 ID]/[레파지토리 name]가 주어집니다.
  • 기본적으로 home을 github.com/[깃허브 ID]/ 로 설정하기 때문에, 첫 시작 url을 github.com/[깃허브 ID]/[레파지토리 name]로 바꾸는 과정이 필요합니다.
  • React Router의 BrowswerRouter - basename 설정
    ReactDOM.render(
    <BrowserRouter basename="[레파지토리 name]">
    <App />
    </BrowserRouter>,
    document.getElementById('root'),
    );

4. 제공된 url 접속해 release branch 적용됐는지 확인

github url

profile
데이원컴퍼니 프론트엔드 개발자입니다.

0개의 댓글