문제 상황

nohup node ./node_modules/@vue/cli-service/bin/vue-cli-service serve --port [PORT] &
nohup python manage.py runserver [IP]:[PORT] --settings=main.config.settings.debug

위의 명령으로 사이트를 서버에 백그라운드로 실행하고 있다고 생각했는데..
때때로 웹이 내려가는 이슈가 발생했다.

 

원인

잘못된 명령어로 인해서 사실 백그라운드로 실행이 안 되고 있는게 아닐까? 라는 생각이 들어서

왜 그러는지 실행할 때 명령을 다시 살펴봤더니

띄울 때 장고 실행에 & 를 붙이지 않고 실행해서 터미널 세션을 닫으면 프로세스도 같이 종료되었던 것이었다..

nohup python manage.py runserver [IP]:[PORT] --settings=main.config.settings.debug

 

해결방법

1. 띄울 때 & 를 잊지 말자!

nohup python manage.py runserver [IP]:[PORT] --settings=main.config.settings.debug &

 

2. 프로세스 모니터 크론잡 등록

서버가 아예 재부팅 되거나 그럴 수도 있으니까
크론잡으로 5분마다 프로세스가 내려가 있는지 체크하고 내려가 있으면 자동으로 올려주도록 스크립트를 등록한다.

#!/usr/bin/env bash

# 로그 파일 위치
LOG_DIRECTORY="/home1/irteamsu/cronjob/logs"
LOG_FILE="$LOG_DIRECTORY/logfile_$(date "+%Y%m%d_%H").log"

# 확인할 프로세스
PYTHON_PROCESS="/home1/irteamsu/.pyenv/versions/py39/bin/python manage.py runserver [IP]:[PORT] --settings=main.config.settings.debug"
NODE_PROCESS="node ./node_modules/@vue/cli-service/bin/vue-cli-service serve --port [PORT]"

# 실행할 디렉토리
PROCESS_DIRECTORY="/home1/irteamsu/variable-comparison"

# 로그에 남길 현재시각
log_current_time() {
    current_time=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$current_time] $1" >> "$LOG_FILE"
}

# 현재 시간을 시간 단위로 구하기
current_hour=$(date "+%H")

# 이전 시간대의 로그 파일 유지, 나머지 로그 파일 삭제
for ((hour=0; hour<current_hour; hour++)); do
    if [ "$hour" -lt 10 ]; then
        rm "$LOG_DIRECTORY/logfile_$(date "+%Y%m%d_0$hour").log" 2>/dev/null
    else
        rm "$LOG_DIRECTORY/logfile_$(date "+%Y%m%d_$hour").log" 2>/dev/null
    fi
done

# python 프로세스 실행 중인지 확인
if pgrep -f "$PYTHON_PROCESS" >/dev/null; then
    log_current_time "Python process is already running."
else
    log_current_time "Python process is not running. Starting the process..."
    source ~/.bash_profile
    cd "$PROCESS_DIRECTORY"
    pyenv activate py39
    nohup /home1/irteamsu/.pyenv/versions/py39/bin/python manage.py runserver [IP]:[PORT] --settings=main.config.settings.debug > /dev/null 2>&1 &
    if pgrep -f "$PYTHON_PROCESS" >/dev/null; then
        log_current_time "Python process started."
    else
    log_current_time "Failed to start Python process."
    fi
fi

# node 프로세스 실행 중인지 확인
if pgrep -f "$NODE_PROCESS" >/dev/null; then
    log_current_time "Node.js process is already running."
else
    log_current_time "Node.js process is not running. Starting the process..."
    cd "$PROCESS_DIRECTORY"
    nohup node ./node_modules/@vue/cli-service/bin/vue-cli-service serve --port [PORT] > /dev/null 2>&1 &
    if pgrep -f "$NODE_PROCESS" >/dev/null; then
        log_current_time "Node.js process started."
    else
        log_current_time "Failed to start Node.js process."
    fi
fi
*/5 * * * * ~/cronjob/background_process_monitor.sh

 

결과

  • 로그 파일 생성 후 1시간 동안만 보관
    • 크게 유의미한 로그가 아니기 때문에 오래 보관할 필요가 없다.

  • 프로세스가 종료된 경우 자동으로 웹이 다시 올라오게 된다!

+ Recent posts