Build and Push Docker Image
name: Build and Deploy
on:
push:
branches: [main]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=sha,prefix=
type=raw,value=latest
- name: Build and push image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=maxDeploy via SSH
deploy:
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy to server
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
docker stop app || true
docker rm app || true
docker run -d \
--name app \
--restart unless-stopped \
-p 3000:3000 \
--env-file /opt/app/.env \
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latestEnvironment Protection Rules
In GitHub Settings → Environments, create a production environment with:
- Required reviewers — someone must approve before production deploy
- Wait timer — enforce a delay after staging passes
- Deployment branches — only
maincan deploy to production
deploy-production:
needs: deploy-staging
environment: production # triggers approval gate
runs-on: ubuntu-latest
steps:
- run: ./deploy-prod.shStore server credentials in GitHub Secrets (Settings → Secrets → Actions), never in the workflow YAML.