How to Use Git for Deployment
Git lets you deploy code changes by pushing from your local machine directly to your server.
Basic Git Deployment via SSH
Step 1: Initialise a Bare Repository on the Server
mkdir ~/repos/mysite.git
cd ~/repos/mysite.git
git init --bare
Step 2: Create a Post-Receive Hook
nano ~/repos/mysite.git/hooks/post-receive
Add:
#!/bin/bash
GIT_WORK_TREE=~/public_html git checkout -f
echo "Deployed successfully!"
Make it executable:
chmod +x ~/repos/mysite.git/hooks/post-receive
Step 3: Add the Server as a Remote (Local Machine)
git remote add production ssh://yourusername@your-domain.com/~/repos/mysite.git
Step 4: Deploy
git push production main
Your files are automatically deployed to ~/public_html/.
Using GitHub Actions for CI/CD
For automated deployments on push to GitHub:
- Add your server's SSH key to GitHub Secrets.
- Create
.github/workflows/deploy.yml:
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy via SSH
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
cd ~/public_html
git pull origin main
composer install --no-dev