update #15
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| name: Safe MERN Deployment | |
| on: | |
| push: | |
| branches: | |
| - main | |
| jobs: | |
| deploy: | |
| runs-on: ubuntu-latest | |
| steps: | |
| - name: Checkout Code | |
| uses: actions/checkout@v3 | |
| - name: Deploy to Ubuntu Server via SSH | |
| uses: appleboy/[email protected] | |
| with: | |
| host: ${{ secrets.SERVER_IP }} | |
| username: ${{ secrets.SERVER_USER }} | |
| key: ${{ secrets.SERVER_SSH_KEY }} | |
| port: 22 | |
| timeout: 30s | |
| command_timeout: 10m | |
| script: | | |
| echo "π Step 1: Create temp folder and clone" | |
| rm -rf /home/hostapp/temp_mern_deploy | |
| git clone https://github.com/React-Testing/React-02.git /home/hostapp/temp_mern_deploy | |
| echo "π¦ Step 2: Install and run backend temporarily" | |
| cd /home/hostapp/temp_mern_deploy/backend | |
| npm install | |
| PORT=5001 pm2 start server.js --name temp-mern-backend --env production | |
| sleep 5 | |
| echo "π Step 3: Check if backend is running" | |
| BACKEND_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:5001/api/test) | |
| if [ "$BACKEND_STATUS" -ge 200 ] && [ "$BACKEND_STATUS" -lt 400 ]; then | |
| echo "β Backend is running fine (HTTP $BACKEND_STATUS)" | |
| else | |
| echo "β Backend check failed with code $BACKEND_STATUS" | |
| pm2 delete temp-mern-backend | |
| exit 1 | |
| fi | |
| echo "π Step 4: Build frontend" | |
| cd /home/hostapp/temp_mern_deploy/frontend | |
| npm install | |
| npm run build | |
| if [ ! -f dist/index.html ]; then | |
| echo "β Frontend build failed" | |
| pm2 delete temp-mern-backend | |
| exit 1 | |
| fi | |
| echo "π Step 5: Backup current project" | |
| TIMESTAMP=$(date +%Y%m%d%H%M%S) | |
| mv /home/hostapp/React-02 /home/hostapp/backup_React-02_$TIMESTAMP | |
| echo "π Step 6: Deploy new code" | |
| mv /home/hostapp/temp_mern_deploy /home/hostapp/React-02 | |
| echo "π₯ Step 7: Restart backend" | |
| pm2 delete temp-mern-backend | |
| cd /home/hostapp/React-02/backend | |
| pm2 start server.js --name mern-backend | |
| echo "π Step 8: Deploy frontend to Nginx root" | |
| rm -rf /opt/day07/* | |
| cp -r /home/hostapp/React-02/frontend/dist/* /opt/day07/ | |
| echo "π Step 9: Restart Nginx" | |
| sudo systemctl restart nginx | |
| echo "β CI/CD Deployment Completed Successfully!" |