Skip to content

Instantly share code, notes, and snippets.

@sorinmircea
Created October 16, 2025 19:22
Show Gist options
  • Save sorinmircea/6e39ed548cb107dd19eaa4413a4dac3d to your computer and use it in GitHub Desktop.
Save sorinmircea/6e39ed548cb107dd19eaa4413a4dac3d to your computer and use it in GitHub Desktop.
Automatically deploy docker based services from git repository
#!/bin/bash
# Parse command-line arguments
FORCE=false
while [[ "$#" -gt 0 ]]; do
case $1 in
--force) FORCE=true ;;
*) echo "Unknown parameter passed: $1"; exit 1 ;;
esac
shift
done
# Function to check for new commits and pull the latest changes
check_and_pull() {
if [[ "$FORCE" == true ]]; then
echo "Force flag detected. Skipping Git check and proceeding with deployment."
return 0 # Force override, so always proceed
fi
echo "Checking for new commits..."
git fetch origin
# Compare local and remote branches
LOCAL_COMMIT=$(git rev-parse HEAD)
REMOTE_COMMIT=$(git rev-parse origin/$(git rev-parse --abbrev-ref HEAD))
if [ "$LOCAL_COMMIT" != "$REMOTE_COMMIT" ]; then
echo "New commits found. Pulling the latest changes..."
git pull
return 0 # Return 0 to indicate that new changes were pulled
else
echo "No new commits found."
return 1 # Return 1 to indicate that no new changes were pulled
fi
}
# Function to process Docker files
process_docker_files() {
echo "Scanning for Docker deployment files..."
# Find directories containing docker-stack.yaml or docker-compose.yaml
find . -type f \( -name "docker-stack.yaml" -o -name "docker-compose.yaml" \) | while read -r file; do
dir=$(dirname "$file")
cd "$dir" || continue
# Generate a valid stack name from the directory name
stack_name=$(basename "$dir" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]//g')
if [[ -f "docker-stack.yaml" ]]; then
echo "Found docker-stack.yaml in $(pwd), deploying stack '$stack_name'..."
docker stack deploy -c docker-stack.yaml "$stack_name" --detach=false --with-registry-auth
elif [[ -f "docker-compose.yaml" ]]; then
echo "Found docker-compose.yaml in $(pwd), restarting services..."
docker-compose down && docker-compose up -d --build
fi
cd - > /dev/null # Return to the previous directory
done
echo "All Docker deployments processed."
}
# Main script
echo "Starting the process..."
# Step 1: Check if there are new commits to pull or force deploy
if check_and_pull; then
# Step 2: Process Docker deployment files
process_docker_files
else
echo "Skipping Docker deployments."
fi
echo "Process completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment