68 lines
2.0 KiB
Bash
Executable File
68 lines
2.0 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Restart docker-compose stack (or selected services) and log output.
|
|
# Usage:
|
|
# ./restart_containers.sh [service1 service2 ...]
|
|
#
|
|
# Env vars:
|
|
# COMPOSE_FILE: override compose file (default: docker-compose.yml)
|
|
|
|
set -euo pipefail
|
|
|
|
REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
LOG_DIR="$REPO_DIR/logs"
|
|
mkdir -p "$LOG_DIR"
|
|
|
|
timestamp() {
|
|
date +"%Y-%m-%d %H:%M:%S%z"
|
|
}
|
|
|
|
echo "[$(timestamp)] Starting restart_containers.sh" | tee -a "$LOG_DIR/restart.log"
|
|
|
|
# Detect compose command
|
|
detect_compose_cmd() {
|
|
if command -v docker >/dev/null 2>&1; then
|
|
if docker compose version >/dev/null 2>&1; then
|
|
echo "docker compose"
|
|
return 0
|
|
fi
|
|
fi
|
|
if command -v docker-compose >/dev/null 2>&1; then
|
|
echo "docker-compose"
|
|
return 0
|
|
fi
|
|
echo "[$(timestamp)] ERROR: Neither 'docker compose' nor 'docker-compose' found in PATH" | tee -a "$LOG_DIR/restart.log"
|
|
exit 1
|
|
}
|
|
|
|
COMPOSE_CMD=$(detect_compose_cmd)
|
|
COMPOSE_FILE_PATH=${COMPOSE_FILE:-docker-compose.yml}
|
|
|
|
if [ ! -f "$REPO_DIR/$COMPOSE_FILE_PATH" ]; then
|
|
echo "[$(timestamp)] ERROR: Compose file not found: $REPO_DIR/$COMPOSE_FILE_PATH" | tee -a "$LOG_DIR/restart.log"
|
|
exit 1
|
|
fi
|
|
|
|
cd "$REPO_DIR"
|
|
|
|
SERVICES=("$@")
|
|
|
|
if [ ${#SERVICES[@]} -eq 0 ]; then
|
|
echo "[$(timestamp)] Restarting full stack using $COMPOSE_FILE_PATH" | tee -a "$LOG_DIR/restart.log"
|
|
set +e
|
|
$COMPOSE_CMD -f "$COMPOSE_FILE_PATH" down >>"$LOG_DIR/restart.log" 2>&1
|
|
DOWN_STATUS=$?
|
|
set -e
|
|
echo "[$(timestamp)] docker compose down exit status: $DOWN_STATUS" | tee -a "$LOG_DIR/restart.log"
|
|
$COMPOSE_CMD -f "$COMPOSE_FILE_PATH" up -d >>"$LOG_DIR/restart.log" 2>&1
|
|
echo "[$(timestamp)] Stack brought up" | tee -a "$LOG_DIR/restart.log"
|
|
else
|
|
echo "[$(timestamp)] Restarting services: ${SERVICES[*]} using $COMPOSE_FILE_PATH" | tee -a "$LOG_DIR/restart.log"
|
|
$COMPOSE_CMD -f "$COMPOSE_FILE_PATH" restart "${SERVICES[@]}" >>"$LOG_DIR/restart.log" 2>&1
|
|
echo "[$(timestamp)] Services restarted" | tee -a "$LOG_DIR/restart.log"
|
|
fi
|
|
|
|
echo "[$(timestamp)] Completed restart_containers.sh" | tee -a "$LOG_DIR/restart.log"
|
|
|
|
|