Update digitalocean-deploy.yml #111
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Build and Push Docker Image to DigitalOcean Droplet | |
on: | |
push: | |
branches: | |
- master | |
- main | |
jobs: | |
deploy: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout repository | |
uses: actions/checkout@v4 | |
- name: Cache Docker layers | |
id: docker-cache | |
uses: actions/cache@v3 | |
with: | |
path: /tmp/.docker-cache | |
key: "${{ runner.os }}-docker-${{ hashFiles('**/Dockerfile', '**/*.csproj') }}" | |
restore-keys: | | |
${{ runner.os }}-docker- | |
- name: Set up Docker Image Tag | |
run: | | |
echo "IMAGE_TAG=todoapp:$(date +%s)-${GITHUB_SHA::8}" >> $GITHUB_ENV | |
- name: Build Docker image | |
run: | | |
docker build --cache-from=type=local,src=/tmp/.docker-cache -t "${{ env.IMAGE_TAG }}" . | |
echo "Docker image built successfully:" | |
docker image ls --format "{{.Repository}}:{{.Tag}}" | grep "todoapp" || echo "Warning: Image not found in list, but build completed" | |
- name: Save Docker image to a tar file | |
run: | | |
docker save ${{ env.IMAGE_TAG }} -o image.tar | |
ls -lh image.tar | |
- name: Setup SSH | |
run: | | |
mkdir -p ~/.ssh | |
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa | |
chmod 600 ~/.ssh/id_rsa | |
ssh-keyscan -H ${{ secrets.DROPLET_IP }} >> ~/.ssh/known_hosts | |
- name: Transfer docker image and docker-compose.yml | |
run: | | |
scp -i ~/.ssh/id_rsa image.tar docker-compose.yml ${{ secrets.DROPLET_USERNAME }}@${{ secrets.DROPLET_IP }}:/home/${{ secrets.DROPLET_USERNAME }}/ | |
- name: SSH into Droplet and Deploy using Docker Compose | |
env: | |
IMAGE_TAG: ${{ env.IMAGE_TAG }} | |
MONGO_CONNECTION_STRING: ${{ secrets.MONGO_CONNECTION_STRING }} | |
MONGO_DATABASE_NAME: ${{ secrets.MONGO_DATABASE_NAME }} | |
MONGO_COLLECTION_NAME: ${{ secrets.MONGO_COLLECTION_NAME }} | |
run: | | |
ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=10 -i ~/.ssh/id_rsa ${{ secrets.DROPLET_USERNAME }}@${{ secrets.DROPLET_IP }} << EOF | |
set -e | |
echo "Starting deployment process..." | |
cd /home/${{ secrets.DROPLET_USERNAME }} | |
echo "Stopping existing container if it exists..." | |
if [ "\$(sudo docker ps -q -f name=todo-app)" ]; then | |
sudo docker compose down | |
fi | |
echo "Loading Docker image..." | |
sudo docker load -i image.tar | |
echo "Running Docker Compose with environment variables..." | |
sudo -E IMAGE_TAG=${{ env.IMAGE_TAG }} \ | |
MONGO_CONNECTION_STRING=${{ env.MONGO_CONNECTION_STRING }} \ | |
MONGO_DATABASE_NAME=${{ env.MONGO_DATABASE_NAME }} \ | |
MONGO_COLLECTION_NAME=${{ env.MONGO_COLLECTION_NAME }} \ | |
docker compose up -d | |
echo "Cleaning up..." | |
rm -f image.tar | |
echo "Deployment completed successfully!" | |
EOF |