diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index 7c9d3627..7a38b897 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -30,8 +30,19 @@ jobs: id: image_tag run: echo "IMAGE_TAG=$(date +'%Y-%m-%d_%H-%M-%S')-$(echo ${{ github.sha }} | cut -c1-8)" >> $GITHUB_ENV - - name: Build and Push Docker image - run: docker buildx build --push --platform linux/amd64 -t kimsongmok/splanet:${{ env.IMAGE_TAG }} . + - name: Decode env.properties from GitHub Secrets + run: | + echo "${{ secrets.ENV_FILE }}" | base64 --decode > ./src/main/resources/env.properties + + - name: Transfer env.properties to EC2 + uses: appleboy/scp-action@v0.1.3 + with: + host: ${{ secrets.EC2_HOST }} + username: ubuntu + key: ${{ secrets.EC2_SSH_KEY }} + source: "./env.properties" + target: "/home/ubuntu/" + - name: Deploy to EC2 uses: appleboy/ssh-action@v0.1.6 @@ -43,15 +54,29 @@ jobs: sudo docker pull kimsongmok/splanet:${{ env.IMAGE_TAG }} sudo docker stop splanet || true sudo docker rm splanet || true + sudo docker network inspect splanet >/dev/null 2>&1 || sudo docker network create splanet + scp ./src/main/resources/env.properties ubuntu@${{ secrets.EC2_HOST }}:/home/ubuntu/env.properties sudo docker run -d --name splanet \ - --network splanet \ - -e MYSQL_PROD_URL=${{ secrets.MYSQL_PROD_URL }} \ - -e MYSQL_PROD_USER=${{ secrets.MYSQL_PROD_USER }} \ - -e MYSQL_PROD_PASSWORD=${{ secrets.MYSQL_PROD_PASSWORD }} \ - -e MYSQL_DATABASE=${{ secrets.MYSQL_DATABASE }} \ - -e CLIENT_ID=${{ secrets.CLIENT_ID }} \ - -e CLIENT_SECRET=${{ secrets.CLIENT_SECRET }} \ - -e JWT_SECRET=${{ secrets.JWT_SECRET }} \ - -e REDIRECT_URL=${{ secrets.REDIRECT_URL }} \ - -p 80:8080 --restart unless-stopped kimsongmok/splanet:${{ env.IMAGE_TAG }}\ - -v ./src/main/resources/env.properties \ No newline at end of file + --network splanet \ + --env-file /home/ubuntu/env.properties \ + -p 80:8080 --restart unless-stopped kimsongmok/splanet:${{ env.IMAGE_TAG }} + + - name: Check Docker container status + uses: appleboy/ssh-action@v0.1.6 + with: + host: ${{ secrets.EC2_HOST }} + username: ubuntu + key: ${{ secrets.EC2_SSH_KEY }} + script: | + sudo docker ps -a + sudo docker logs splanet + + - name: Clean up old Docker images + uses: appleboy/ssh-action@v0.1.6 + with: + host: ${{ secrets.EC2_HOST }} + username: ubuntu + key: ${{ secrets.EC2_SSH_KEY }} + script: | + docker image ls --format "{{.ID}} {{.Repository}}:{{.Tag}}" | grep 'kimsongmok/splanet' | tail -n +4 | awk '{print $1}' | xargs docker rmi -f + sudo docker system prune -f