DevOps

[Jenkins] Jenkins로 nginx + react 빌드 및 배포하기

땅지원 2023. 2. 3. 14:10

react 배포 준비

npm run build 명령어를 통해 frontend 프로젝트 build 진행
, script에 따라 build 결과 생기는 디렉토리가 build가 아니라 dist나 다른 이름의 폴더일 수도 있음을 유의

 

FrontendDockerfileNginx 구성 파일을 작성

nginx.conf

server {
    listen 3000;
    location / {
        root /app/build;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

Dockerfile

# nginx 이미지를 사용합니다. 뒤에 tag가 없으면 latest 를 사용합니다.
FROM nginx

# root 에 app 폴더를 생성
RUN mkdir /app

# work dir 고정
WORKDIR /app

# work dir 에 build 폴더 생성 /app/build
RUN mkdir ./build

# host pc의 현재경로의 build 폴더를 workdir 의 build 폴더로 복사
ADD ./dist ./build

# nginx 의 default.conf 를 삭제
RUN rm /etc/nginx/conf.d/default.conf

# host pc 의 nginx.conf 를 아래 경로에 복사
COPY ./nginx.conf /etc/nginx/conf.d

# 80 포트 오픈
EXPOSE 80

# container 실행 시 자동으로 실행할 command. nginx 시작함
CMD ["nginx", "-g", "daemon off;"]

 

Nginx & SSL 설정

1. Nginx 설치
sudo apt-get install nginx

2. 설치 확인
sudo nginx -v

3. Nginx 중지
sudo systemctl stop nginx

4. Let’s Encrypt 설치
sudo apt-get install letsencrypt

5. 인증서 적용 및 .pem 키 발급(이메일, 서비스 이용동의 체크)
sudo letsencrypt certonly --standalone -d [도메인]
Congratulation!이라는 메시지와 함께 .pem키 발급이 완료된 것을 확인 가능

6. 발급 경로 확인(sudo su)
cd /etc/letsencrypt/live/[도메인]

7. Nginx 설정 파일을 작성
cd /etc/nginx/sites-available
sudo vim [파일명].conf

7. nginx 설정 파일

server {
        location /{
                proxy_pass http://localhost:3000;
        }

        location /api {
                proxy_pass http://localhost:8081/api;
        }
    

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/i8a704.p.ssafy.io/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/i8a704.p.ssafy.io/privkey.pem; # managed by Certbot
    # include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    # ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = i8a704.p.ssafy.io) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        server_name i8a704.p.ssafy.io;
    return 404; # managed by Certbot
}
9. 파일 연동 및 테스트(ok 나오면 됨)
sudo ln -s /etc/nginx/sites-available/[파일명].conf /etc/nginx/sites-enabled/[파일명].conf
sudo nginx -t

10. nginx 재시작
sudo systemctl restart nginx

11. nginx 상태 확인
sudo systemctl status nginx

 

jenkins에서 새로운 아이템을 만들어서 backend 설정과 동일하게 만들고

nodejs 플러그인을 받은다음 node를 넣어주고

 

execute shell에서는

cd /var/jenkins_home/workspace/auctopus-fe/frontend

ls

npm install
npm run build

docker images
docker ps -a

cat Dockerfile

docker build -t auctopus/fe .
docker run -p 3000:3000 --name frontend auctopus/fe