From 4b5711337e9955c70301b3ec61c5fae022ea631c Mon Sep 17 00:00:00 2001 From: Denshooter <44590296+Denshooter@users.noreply.github.com> Date: Mon, 10 Feb 2025 11:04:45 +0100 Subject: [PATCH] Create main.yml --- .github/workflows/main.yml | 66 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 .github/workflows/main.yml diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..11c85a7 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,66 @@ +name: Deploy Next.js to Raspberry Pi + +on: + push: + branches: + - main + - dev + - preview + +jobs: + deploy: + runs-on: self-hosted # Der Runner sollte auf dem Raspberry Pi laufen + + steps: + - name: Checkout Code + uses: actions/checkout@v3 + + - name: Set Environment Variables + run: | + if [[ "${{ github.ref_name }}" == "main" ]]; then + echo "DEPLOY_ENV=main" >> $GITHUB_ENV + echo "PORT=3000" >> $GITHUB_ENV + elif [[ "${{ github.ref_name }}" == "dev" ]]; then + echo "DEPLOY_ENV=dev" >> $GITHUB_ENV + echo "PORT=3001" >> $GITHUB_ENV + elif [[ "${{ github.ref_name }}" == "preview" ]]; then + echo "DEPLOY_ENV=preview" >> $GITHUB_ENV + echo "PORT=3002" >> $GITHUB_ENV + fi + + - name: Build Docker Image + run: | + IMAGE_NAME="my-nextjs-app:$DEPLOY_ENV" + docker build -t $IMAGE_NAME . + + - name: Deploy on Raspberry Pi (Zero-Downtime) + run: | + CONTAINER_NAME="nextjs-$DEPLOY_ENV" + IMAGE_NAME="my-nextjs-app:$DEPLOY_ENV" + NEW_CONTAINER_NAME="$CONTAINER_NAME-new" + + # Pull latest image version if exists + docker pull $IMAGE_NAME || true + + # Run new container on a different port + docker run -d --name "$NEW_CONTAINER_NAME" -p 30000:3000 $IMAGE_NAME + + # Wait to ensure the new container is up and running + sleep 10 + + # Check if new container is healthy and running + if [ $(docker inspect --format='{{.State.Running}}' $NEW_CONTAINER_NAME) == "true" ]; then + # Stop and remove the old container + docker stop "$CONTAINER_NAME" || true + docker rm "$CONTAINER_NAME" || true + + # Rename new container to the old container’s name + docker rename "$NEW_CONTAINER_NAME" "$CONTAINER_NAME" + + # Reassign the desired port (e.g., 3000 for main branch) to the new container + docker run -d --name "$CONTAINER_NAME" -p $PORT:3000 $IMAGE_NAME + else + echo "New container failed to start." + docker logs $NEW_CONTAINER_NAME + exit 1 + fi