깃허브에 코드를 푸시할 때마다 수동으로 서버에 접속해 배포하는 과정이 얼마나 번거로운지 경험해봤을까. 대부분의 개발팀은 이 반복적인 작업을 자동화하려다가 설정 파일 오류, 보안 키 관리, 배포 실패 대응으로 며칠을 낭비한다. 이번에는 GitHub Actions를 활용해 PHP 프로젝트를 자동으로 테스트하고, 빌드하고, 프로덕션 서버에 배포하는 완전한 CI/CD 파이프라인을 완벽하게 정리해서 소개하겠다.
CI(Continuous Integration)는 개발자들이 작성한 코드를 주기적으로 통합해 자동 테스트와 빌드를 수행하는 것이고, CD(Continuous Deployment)는 그렇게 만든 빌드 결과물을 자동으로 프로덕션 환경에 배포하는 것이다. 두 단계를 조합하면 버그 조기 발견, 배포 시간 단축, 휴먼 에러 제거 같은 이점을 얻을 수 있다.
다음은 PHP 프로젝트용 기본 워크플로우 구조다.
name: PHP CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
php-version: ['8.1', '8.2']
steps:
- uses: actions/checkout@v3
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
extensions: mbstring, pdo, pdo_mysql, json
- name: Install dependencies
run: composer install --no-interaction --prefer-dist
- name: Run PHPUnit tests
run: vendor/bin/phpunit
- name: Run PHP CodeSniffer
run: vendor/bin/phpcs --standard=PSR12 src/
✓ 올바른 구성: 이 파일은 main과 develop 브랜치에 푸시될 때마다 PHP 8.1과 8.2 양쪽에서 테스트를 실행한다. 필요한 확장 모듈을 미리 설치하고, Composer로 의존성을 받은 후, PHPUnit과 CodeSniffer를 차례로 실행한다.
✗ 흔한 실수: PHP 버전을 명시하지 않거나, 필요한 확장 모듈 설정을 빠뜨리면 `Call to undefined function` 같은 에러가 발생한다. 또한 `composer install`을 빠뜨리면 의존성이 로드되지 않아 테스트가 실패한다.
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
steps:
- uses: actions/checkout@v3
- name: Deploy to production
env:
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
run: |
mkdir -p ~/.ssh
echo "$DEPLOY_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts
ssh -i ~/.ssh/deploy_key $DEPLOY_USER@$DEPLOY_HOST "cd $DEPLOY_PATH && git pull origin main && composer install --no-dev && php artisan migrate --force"
✓ 올바른 배포: `needs: test`로 test 작업이 성공해야만 deploy 작업이 실행되도록 의존성을 설정했다. `if: github.ref == 'refs/heads/main'`로 main 브랜치만 배포하도록 제한했고, SSH 키는 GitHub Secrets에서 안전하게 불러온다.
✗ 흔한 실수: SSH 키를 그대로 워크플로우 파일에 작성하거나, Secrets 설정을 건너뛰면 보안 위험이 된다. 또한 `chmod 600`을 빠뜨리면 권한 오류로 SSH 접속이 거부된다.
설정 방법: 저장소의 Settings → Secrets and variables → Actions로 이동해 New repository secret 버튼을 클릭한다. 예를 들어 DEPLOY_KEY, DEPLOY_HOST, DEPLOY_USER, DEPLOY_PATH 같은 항목을 하나씩 등록한다.
# SSH 키 생성 (저장소별 별도 키 권장)
ssh-keygen -t rsa -b 4096 -f deploy_key -N ""
# deploy_key 파일 내용을 DEPLOY_KEY Secret으로 등록
cat deploy_key | pbcopy # macOS
# 또는
cat deploy_key | xclip -selection clipboard # Linux
deploy-staging:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/develop' && github.event_name == 'push'
steps:
- uses: actions/checkout@v3
- name: Deploy to staging
env:
DEPLOY_KEY: ${{ secrets.STAGING_DEPLOY_KEY }}
DEPLOY_HOST: ${{ secrets.STAGING_HOST }}
DEPLOY_USER: ${{ secrets.STAGING_USER }}
DEPLOY_PATH: ${{ secrets.STAGING_PATH }}
run: |
mkdir -p ~/.ssh
echo "$DEPLOY_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts
ssh -i ~/.ssh/deploy_key $DEPLOY_USER@$DEPLOY_HOST "cd $DEPLOY_PATH && git pull origin develop && composer install && php artisan migrate"
deploy-production:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
steps:
- uses: actions/checkout@v3
- name: Deploy to production
env:
DEPLOY_KEY: ${{ secrets.PROD_DEPLOY_KEY }}
DEPLOY_HOST: ${{ secrets.PROD_HOST }}
DEPLOY_USER: ${{ secrets.PROD_USER }}
DEPLOY_PATH: ${{ secrets.PROD_PATH }}
run: |
mkdir -p ~/.ssh
echo "$DEPLOY_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts
ssh -i ~/.ssh/deploy_key $DEPLOY_USER@$DEPLOY_HOST "cd $DEPLOY_PATH && git pull origin main && composer install --no-dev && php artisan migrate --force"
1. 타임아웃: 배포 작업이 너무 오래 걸리면 타임아웃된다. `composer install` 중 패키지 다운로드가 오래 걸리는 경우 `timeout-minutes` 옵션으로 제한 시간을 늘린다.
deploy:
timeout-minutes: 15
runs-on: ubuntu-latest
2. 배포 중 에러 발생 시 롤백: 배포 후 애플리케이션이 시작되지 않으면 롤백해야 한다. 배포 전 현재 버전을 백업하고, 에러 발생 시 복구한다.
ssh -i ~/.ssh/deploy_key $DEPLOY_USER@$DEPLOY_HOST "cd $DEPLOY_PATH && git stash && git pull origin main || (git checkout - && exit 1)"
3. 데이터베이스 마이그레이션 실패: 마이그레이션이 롤백되지 않아 배포 후 상태 불일치가 발생할 수 있다. `--force` 플래그를 추가하되, 프로덕션에서는 신중하게 사용한다.
- name: Notify on failure
if: failure()
uses: slackapi/slack-github-action@v1
with:
webhook-url: ${{ secrets.SLACK_WEBHOOK }}
payload: |
{
"text": "배포 실패: ${{ github.repository }} - ${{ github.ref }}",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*배포 작업 실패*\n저장소: ${{ github.repository }}\n브랜치: ${{ github.ref }}\nURL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
}
}
]
}
name: Complete PHP CI/CD
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
php-version: ['8.1', '8.2']
services:
mysql:
image: mysql:8.0
env:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: test_db
options: >-
--health-cmd="mysqladmin ping"
--health-interval=10s
--health-timeout=5s
--health-retries=3
ports:
- 3306:3306
steps:
- uses: actions/checkout@v3
- name: Setup PHP ${{ matrix.php-version }}
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
extensions: mbstring, pdo, pdo_mysql, json, curl
tools: composer:v2
- name: Get composer cache directory
id: composer-cache
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
- name: Cache dependencies
uses: actions/cache@v3
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install dependencies
run: composer install --no-interaction --prefer-dist
- name: Run tests
run: vendor/bin/phpunit --coverage-text
env:
DB_HOST: 127.0.0.1
DB_PORT: 3306
DB_DATABASE: test_db
DB_USERNAME: root
DB_PASSWORD: root
- name: Run code style check
run: vendor/bin/phpcs --standard=PSR12 src/ || true
deploy-staging:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/develop'
timeout-minutes: 15
steps:
- uses: actions/checkout@v3
- name: Deploy to staging server
env:
DEPLOY_KEY: ${{ secrets.STAGING_DEPLOY_KEY }}
DEPLOY_HOST: ${{ secrets.STAGING_HOST }}
DEPLOY_USER: ${{ secrets.STAGING_USER }}
DEPLOY_PATH: ${{ secrets.STAGING_PATH }}
run: |
mkdir -p ~/.ssh
echo "$DEPLOY_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts 2>/dev/null
ssh -i ~/.ssh/deploy_key $DEPLOY_USER@$DEPLOY_HOST "cd $DEPLOY_PATH && git pull origin develop && composer install && php artisan migrate"
- name: Notify deployment
if: success()
uses: slackapi/slack-github-action@v1
with:
webhook-url: ${{ secrets.SLACK_WEBHOOK }}
payload: |
{"text": "스테이징 배포 완료: ${{ github.ref }}"}
deploy-production:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
timeout-minutes: 15
steps:
- uses: actions/checkout@v3
- name: Deploy to production server
env:
DEPLOY_KEY: ${{ secrets.PROD_DEPLOY_KEY }}
DEPLOY_HOST: ${{ secrets.PROD_HOST }}
DEPLOY_USER: ${{ secrets.PROD_USER }}
DEPLOY_PATH: ${{ secrets.PROD_PATH }}
run: |
mkdir -p ~/.ssh
echo "$DEPLOY_KEY" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -H $DEPLOY_HOST >> ~/.ssh/known_hosts 2>/dev/null
ssh -i ~/.ssh/deploy_key $DEPLOY_USER@$DEPLOY_HOST "cd $DEPLOY_PATH && git pull origin main && composer install --no-dev && php artisan migrate --force"