hye-log

Nginx-SpringBoot 무중단 배포 도입기 - (2) actuator 본문

Infra/Nginx

Nginx-SpringBoot 무중단 배포 도입기 - (2) actuator

iihye_ 2024. 4. 14. 03:03

서론 없이 바로 삽질한 내용들 갑니다!

 

1. Jenkins 생성

Jenkins는 만들던 대로 만들면 된다

webhook 걸어서 git에 push하면

Jenkins도 동작하도록 설정하기!

 

2. nginx 설정 변경

(blue)port 9091 -> (green)port 9092 로 넘어가도록 구성할 것이다

우선 nginx에게 포트가 변경되는 것을 알려주기 위해서

service-url.inc 파일을 하나 생성해서  url을 변경해준다

sudo vi /etc/nginx/conf.d/service-url.inc

/etc/nginx/conf.d에 service-url을 만들 파일을 하나 생성하고

set $service_url http://127.0.0.1:9091

위와 같이 백엔드 주소를 입력해준다

무중단 배포 sh 파일을 통해 여기에 있는 포트번호 9091을 9092로 바꿔줄 것이다

server {
    listen 80; 
    server_name {{도메인}}; 
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name {{도메인}};

    ssl_certificate {{pem키}};
    ssl_certificate_key {{pem키}};

    location /api2 { 
        include /etc/nginx/conf.d/service-url.inc;
        proxy_pass $service_url;
        proxy_redirect off;
        charset utf-8;
        proxy_http_version 1.1;
        proxy_set_header Connection "upgrade";
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-NginX-Proxy true;
    }
}

/etc/nginx/sites-available/nginx.conf 파일에도

위와 같이 입력해준다

(당연히 sites-enabled에 링크가 걸려 있는 상태이다)

 

3. controller 생성

@RestController
@RequiredArgsConstructor
@RequestMapping("/api2/test")
public class WebRestController {

    private final Environment env;

    @GetMapping("/profile")
    public String getProfile() {
        return Arrays.stream(env.getActiveProfiles())
            .findFirst()
            .orElse("");
    }
}

현재 어떤 profile을 사용하고 있는지 api를 통해 알 수 있도록

api2/test/profile api를 생성한다

postman을 이용하여 테스트했을 때

다음과 같이 잘 나오는 것을 볼 수 있다

참고로 prod1은 blue로 설정한 profile의 이름이다

 

4. actuator 설정

서버의 상태를 확인할 수 있는 actuator를 이용하여 포트를 바꿀지 결정할 것이다

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
}

build.gradle에 다음과 같이 dependency를 추가한다

 

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    // 권한 규칙 작성
    http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/actuator/**").permitAll()
            .anyRequest().authenticated()
	);

    return http.build();
}

Spring Security로 인가된 주소 외에는 반드시 로그인 해야 하는데,

원래는 관리자 계정을 생성하고 관리자 권한으로만 실행하게 해야 맞다

우리는 구현에 목적을 두었기 때문에 관리자 권한은 생략하고,

actuator에 접근할 때에는 인증을 요구하지 않도록 구현했다

Spring Security를 설정한 상태에서 이 부분이 해결되지 않으면 지속적으로 401 에러가 발생한다

 

이렇게 포트를 바꾸기 전에 서버 상태를 체크할 수 있는 actuator 설정까지 완료했다

728x90
Comments