name: Deploy Next.js to Raspberry Pi on: push: branches: - production - dev - preview jobs: deploy: runs-on: self-hosted # Der Runner sollte auf dem Raspberry Pi laufen steps: - name: Checkout Code uses: actions/checkout@v4 - name: Set Environment Variables run: | if [[ "${{ github.ref_name }}" == "production" ]]; then echo "DEPLOY_ENV=production" >> $GITHUB_ENV echo "PORT=4000" >> $GITHUB_ENV elif [[ "${{ github.ref_name }}" == "dev" ]]; then echo "DEPLOY_ENV=dev" >> $GITHUB_ENV echo "PORT=4001" >> $GITHUB_ENV elif [[ "${{ github.ref_name }}" == "preview" ]]; then echo "DEPLOY_ENV=preview" >> $GITHUB_ENV echo "PORT=4002" >> $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" # Remove existing temporary container, if any if [ "$(docker ps -aq -f name=$NEW_CONTAINER_NAME)" ]; then echo "Removing existing new container ($NEW_CONTAINER_NAME)..." docker rm -f "$NEW_CONTAINER_NAME" || true fi # Start the new container on a temporary internal port docker run -d --name "$NEW_CONTAINER_NAME" -p 40000:3000 \ -e GHOST_API_KEY="${{ secrets.GHOST_API_KEY }}" \ $IMAGE_NAME # Wait to ensure the new container is running sleep 10 # Check if the new container is running successfully if [ "$(docker inspect --format='{{.State.Running}}' $NEW_CONTAINER_NAME)" == "true" ]; then # Stop and remove the old container, if any if [ "$(docker ps -aq -f name=$CONTAINER_NAME)" ]; then docker stop "$CONTAINER_NAME" || true docker rm "$CONTAINER_NAME" || true fi # Stop and remove the temporary new container docker stop "$NEW_CONTAINER_NAME" || true docker rm "$NEW_CONTAINER_NAME" || true # Start the container with the desired name and port docker run -d --name "$CONTAINER_NAME" -p $PORT:3000 \ -e GHOST_API_KEY="${{ secrets.GHOST_API_KEY }}" \ $IMAGE_NAME else echo "New container failed to start." docker logs $NEW_CONTAINER_NAME exit 1 fi