[CI/CD] Jenkins Pipeline 으로 Docker에 Next.js 프로젝트 이미지 띄우기

RUNGOAT·2023년 6월 18일
0

CI/CD

목록 보기
7/11

1️⃣   Pipeline 설정

새로운 Item 클릭

Pipeline을 선택 후 해당 Pipeline의 이름을 설정하여 생성한다.

하단의 Definition 을 Pipeline script로 선택


2️⃣   Front-end pipeline script

pipeline {
    agent any
    
    tools {nodejs "{Jenkins 관리 - Global Tool Configuration - NodeJS에서 설정한 Name}"}
    
    environment {
        DOCKER_COMPOSE_VERSION = '1.29.2'
    }
    
    stages {
        
        stage('gitlab_clone') {
            steps {
                git branch: 'FE', credentialsId: 'gitlab_token', url: '{GitLab 저장소 주소 HTTPS}'
            }
        }
        
        stage('docker-clean-up') {
            steps {
                script {
                    sshagent(credentials: ['ec2_ssh_key']) {
                    
                    sh '''
                    if test "`docker ps -aq --filter ancestor=front`"; then
                    
					ssh -o StrictHostKeyChecking=no ubuntu@{ec2 서버 도메인 or IP주소} "docker stop $(docker ps -aq --filter ancestor=front)"
                    // 이전 컨테이너 삭제
                    ssh -o StrictHostKeyChecking=no ubuntu@{ec2 서버 도메인 or IP주소} "docker rm -f $(docker ps -aq --filter ancestor=front)"
                    // 이전 이미지 삭제
                    ssh -o StrictHostKeyChecking=no ubuntu@{ec2 서버 도메인 or IP주소} "docker rmi front"

                    fi
                    '''
                    }
                }
                
            }
        }
        
        stage('docker-build'){
            steps {
                script {
                    echo 'Build Docker'
                    dir('ico') {
                        script {
                            
                            sh """
                                if ! command -v docker > /dev/null; then
                                    curl -fsSL https://get.docker.com -o get-docker.sh
                                    sh get-docker.sh
                                fi
                            """
                            
                            sh 'docker-compose -f docker-compose.yml build'
                        }
                    }
                }
            }
        }
        
        stage('Docker run') {
            steps {
                dir('ico') {
                    script {
                        sh 'docker-compose -f docker-compose.yml up -d'
                    }
                }
            }
        }
    }
}

3️⃣   Front 프로젝트 루트 디렉토리에 작성할 것

✔ docker-compose.yml

version: '3'

services:
  app:
    build: .
    image: front
    ports:
      - '3000:3000'
    command: 'npm run start'

✔ Dockerfile

# 기본 이미지 설정
FROM node:18.16.0-alpine

# 작업 디렉토리 설정
WORKDIR /app

# 의존성 파일 복사
COPY package.json package-lock.json ./

# 의존성 설치
RUN npm i

# 소스 코드 복사
COPY . .

# 빌드
RUN npm run build

📌 참고

profile
📞피드백 너무나 환영

0개의 댓글