Skip to content

setup workflow

setup workflow #2

name: Build and Deploy
on:
workflow_dispatch:
push:
branches:
- main
jobs:
build-and-push:
runs-on: ubuntu-latest
environment: ec2
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Cache Docker layers
uses: actions/cache@v2
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
- name: Set up date and tag environment variables
run: |
echo "IMAGE_TAG=$(date +'%Y%m%d')-ec2" >> $GITHUB_ENV
- name: Log in to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push Docker images
run: |
docker buildx build --platform linux/amd64 --cache-from=type=local,src=/tmp/.buildx-cache --cache-to=type=local,dest=/tmp/.buildx-cache --tag an1no/flowchart:latest --push .
deploy:
runs-on: ubuntu-latest
environment: ec2
needs: [build-and-push]
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Set up SSH
uses: webfactory/ssh-agent@v0.5.3
with:
ssh-private-key: ${{ secrets.EC2_KEY }} # Use your EC2 private key from secrets
- name: Deploy Docker container to EC2
run: |
# Connect to the EC2 instance and execute Docker commands
ssh -o StrictHostKeyChecking=no ${{ secrets.EC2_USER }}@${{ secrets.EC2_HOST }} << 'EOF'
# Pull the latest image from Docker Hub
echo "Pulling latest image from Docker Hub..."
docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }}
docker pull an1no/flowchart:latest
# Stop and remove the old container if it exists
echo "Stopping and removing existing container..."
docker stop flowchart-app || true
docker rm flowchart-app || true
# Run the new container
echo "Running new container..."
docker run -d --name flowchart-app -p 80:80 -p 443:443 an1no/flowchart:latest
echo "Deployment complete!"
EOF