프로젝트/SNS를 통한 운동팀 매칭 서비스

배포환경 구축(3) : Nginx Deploy

Mev01 2021. 8. 27. 00:01

이번 포스트에는 위 사진의 표시한 부분을 구현하겠습니다.

 

 

Front Back 관련


# 프론트엔드 빌드
yarn build

# 백엔드 빌드
./mvnw package

# 보안상 외부에서 8080 접근 불가하게 실행하려면 --server.address=127.0.0.1 옵션추가
java -jar target/*.jar --server.servlet.context-path=/api

위 코드로 frontend, backend에서 각각 빌드를 실행하고

backend를 /api로 접근하기 위해서 servlet context 경로를 변경합니다.

 

import org.springframework.boot.context.ApplicationPidFileWriter;

@SpringBootApplication
public class WebCurationApplication {
	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(WebCurationApplication.class);
		app.addListeners(new ApplicationPidFileWriter()); // pid 파일을 생성하는 writer 등록
		app.run(args);
	}
}

pid 파일이 생성되도록  backend에서 WebCurationApplication.java 파일을 변경합니다.

서버 실행 시 자동으로 application.pid 파일이 생성되므로 커밋되지 않도록 .gitignore에 등록합니다.

 

# 운영 서버에서 Backend 재시작 스크립트 생성 및 실행 권한 추가
vi ~/restart_backend1.sh

운영 서버에서 backend 재시작 스크립트 생성 및 실행 권한 추가를 위해

restart_backend1.sh 파일을  아래와 같이 변경합니다.

#!/bin/bash

# SDKMAN only for java
#source "/home/ubuntu/.sdkman/bin/sdkman-init.sh"

kill $(cat app1.pid)

nohup java -jar app1.jar --server.servlet.context-path=/api --server.address=127.0.0.1 --server.port=8080 \
--spring.pid.file=app1.pid >> app1.log 2>&1 &

# pid 생성 기다리기
sleep 2
echo "complate deploy app1 pid=$(cat app1.pid)"

 

# 실행권한 추가 후 테스트
chmod +x ~/restart_backend1.sh
~/restart_backend1.sh

위 코드로 restart_backend1.sh의 실행권한 추가 후 테스트를 진행합니다.

 

 

Nginx 관련


sudo apt install nginx
sudo vi /etc/nginx/sites-enabled/default

Nginx를 설치합니다.

그리고 vi 명령어를 통해 Nginx 설정파일에 들어가 보겠습니다.

 

server {
	# 포트 80으로 연결
        listen 80 default_server;
        listen [::]:80 default_server;

        #root /var/www/html
        root [frontend 빌드해서 생긴 dist 폴더 위치];


        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404 /index.html;
        }

        ##### 여기부터 백엔드 리버스 프록시로 설정 추가
        location /api {
                proxy_pass http://localhost:8080;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $pr:39.oxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header X-Forwarded-Host $host;
                proxy_set_header X-Forwarded-Port $server_port;
        }
        ###### 여기까지
}

설정 파일을 위와 같이 변경합니다.(dist 폴더 위치 조정)

 

 

배포 결과 확인


배포가 끝났습니다.

http://배포주소

http://배포주소/api

위의 주소로 접속해 배포된 frontend, backend를 확인합니다.