This post explains how to handle errors when deploying to production servers after development and testing, and outlines strategies for backup and rollback.
When deploying software to production, unexpected issues can arise at any time, no matter how thoroughly we've tested on the test server. Rather than resorting to prayer, it's crucial to have a strategy in place to deal with such situations.
Before deployment, it's vital to secure the most recent backup of your current system. In the worst-case scenario where server monitoring fails to detect an error, you might need to revert both code and data.
1. TIMESTAMP=`date +%F`
2. cd /home/username/backup
3. rm -rf *.gz
4. rm -rf backup-*
5. mongodump --uri mongodb://127.0.0.1:27017/your-database --out /home/username/backup/backup-$TIMESTAMP
6. tar -zcvf backup-$TIMESTAMP.tar.gz /home/username/backup/backup-$TIMESTAMP
(This is an example backup script assuming the use of MongoDB.)
Additional optional steps could include:
It's good practice to run the DB backup script regularly, not just before deployments. You can set up regular backups using Linux's crontab or pm2, scheduling them to run at set times on the server.
Similarly, environment variable files should also be backed up to the backup folder. This process is simple, so we'll skip the details.
If you've created a backup script, running it before building prepares you for any necessary rollbacks.
#!/bin/bash
# Rollback script
# 1. Code rollback
git reset --hard $PREVIOUS_COMMIT_HASH
git push -f origin main # or relevant branch
# 2. Database rollback
mongorestore --uri mongodb://127.0.0.1:27017/logistics-ko /path/to/backup/directory
# 3. Restore environment config file
cp /path/to/backup/env_file /path/to/production/env_file
# 4. Restart application
echo "Rollback completed"
If you encounter server or database issues that can't be monitored, having a backup allows you to use the above script to return to the pre-deployment state.
Of course, depending on your service's situation, there may be cases where you can't fully use the backup or can't return to the previous state even with a backup. Preparing for such scenarios in advance will reduce deployment interruptions and lead to a better service.
이 포스팅은 개발 후 테스트 서버를 거쳐 prod서버로 배포 시 오류에 대한 대처와 백업과 롤백의 전략을 설명합니다.
소프트웨어 개발 시 프로덕션 배포를 진행할 때 아무리 테스트 서버에서 많은 테스트를 거쳤다고 해도 우리의 의도가 아닌 일은 언제든지 발생할 수 있다. 그럴때 기도하기 보다는 미리 전략을 가지고 대처하는 방법을 가져야한다.
배포를 하기전에 현재 시스템에서 가장 최신의 백업 데이터를 확보하는 것이 중요하다.
서버 모니터링 만으로 오류를 확인할 수 없는경우 최악의 경우 코드와 데이터를 되돌려야 하기 때문이다.
1. TIMESTAMP=`date +%F`
2. cd /home/username/backup
3. rm -rf *.gz
4. rm -rf backup-*
5. mongodump --uri mongodb://127.0.0.1:27017/your-database --out /home/username/backup/backup-$TIMESTAMP
6. tar -zcvf backup-$TIMESTAMP.tar.gz /home/username/backup/backup-$TIMESTAMP
(mongodb를 사용한다는 가정하에 만든 백업 스크립트 예시이다.)
1. 현재날짜를 TIMESTAMP변수에 저장하고
2. 백업 파일을 저장할 디렉토리로 이동한다.
3. 백업 디렉토리에 이전에 저장했을 수 있는 .gz파일을 삭제하여 디스크 공간을 확보한다.
4. 'backup-'로 시작하는 모든 디렉토리를 삭제, 이전 백업 디렉토리를 정리한다.
5. mongodump 명령을 사용하여 데이터베이스의 백업을 생성하고, --uri에 MongoDB 서버의 주소와 데이터베이스 이름을 지정한다. --out은 백업파일이 저장될 경로를 지정한다. 여기서는 날짜가 포함된 디렉토리 이름을 사용한다.
6. 백업 디렉토리를 압축하고 파일명을 지정한다.
추가적인 선택사항으로는
에러 처리 : 각 명령의 실행 결과를 확인하고 실패 시 대응.
로깅 : 백업 과정과 결과를 로그 파일에 기록.
알림 : 백업 성공 또는 실패 시 관리자에게 알림.
db백업 스크립트는 평상시에도 하는게 좋다.
linux의 crontab 또는 pm2를 사용하여 서버에서 매 정해진 시간마다 백업을 할 수 있도록 설정해 두어야 한다.
마찬가지로 환경변수 파일도 백업폴더에 백업을 해야한다. 간단하니 생략.
백업 스크립트를 만들어 뒀다면 빌드하기전에 해당 백업 스크립트를 실행을 시키면 돌아갈 준비는 완료된 것이다.
#!/bin/bash
# 롤백 스크립트
# 1. 코드 롤백
git reset --hard $PREVIOUS_COMMIT_HASH
git push -f origin main # 또는 해당 브랜치
# 2. 데이터베이스 롤백
mongorestore --uri mongodb://127.0.0.1:27017/logistics-ko /path/to/backup/directory
# 3. 환경 설정 파일 복원
cp /path/to/backup/env_file /path/to/production/env_file
# 4. 애플리케이션 재시작
echo "롤백 완료"
서버나 데이터베이스에 문제가 생겼고 모니터링이 되지않을 경우 빌드 이전 미리 백업을 해뒀다면 위 스크립트를 적절히 활용을 하여 다시 배포 이전의 상황으로 돌아갈 수 있다.
물론 서비스의 상황에 따라 백업을 하더라도 그것을 온전히 사용할 수 없는 상황도 있고 이전으로 돌아갈 수 없는 상황도 있을수 있다. 그런 현상도 미리 시뮬레이션을 통해 대비한다면 배포가 중단되는 현상은 줄어들고 보다 나은 서비스가 될것이다.