diff --git a/scripts/check_running_container.sh b/scripts/check_running_container.sh index 2cb09da3..774dfd61 100644 --- a/scripts/check_running_container.sh +++ b/scripts/check_running_container.sh @@ -32,7 +32,10 @@ check_running_container() { exit 1 fi echo "๐Ÿงน Stopping stale container: $NEW_CONTAINER" - stop_and_clean_container "$NEW_CONTAINER" + if ! stop_and_clean_container "$NEW_CONTAINER"; then + echo "โŒ Failed to clean up stale container. Aborting deployment." + exit 1 + fi else local CONTAINER_NAME="${CONTAINERS[0]}" diff --git a/scripts/deploy.sh b/scripts/deploy.sh index a7365f9c..c8606350 100644 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -40,6 +40,9 @@ if ! reload_nginx $NEW_PORT; then fi # 5. Stop and remove the previous container -stop_and_clean_container $RUNNING_CONTAINER +if ! stop_and_clean_container "$RUNNING_CONTAINER"; then + echo "โŒ Deployment switched successfully, but failed to clean up the previous container." + exit 1 +fi echo "โœ… Finish Deploy" diff --git a/scripts/stop_and_clean_container.sh b/scripts/stop_and_clean_container.sh index c6d2c716..b67c96ae 100644 --- a/scripts/stop_and_clean_container.sh +++ b/scripts/stop_and_clean_container.sh @@ -1,13 +1,35 @@ #!/bin/bash +readonly CONTAINER_STOP_TIMEOUT_SECONDS=30 +readonly DOCKER_COMMAND_TIMEOUT_SECONDS=45 + +run_docker_command_with_timeout() { + timeout --kill-after=5s "${DOCKER_COMMAND_TIMEOUT_SECONDS}s" "$@" +} + stop_and_clean_container() { local CONTAINER_NAME=$1 if [ -z "${CONTAINER_NAME}" ]; then echo "โš ๏ธ No container name provided to stop and clean." return 0 fi + echo "๐Ÿ›‘ Stopping and removing container: ${CONTAINER_NAME}" - docker compose stop "${CONTAINER_NAME}" - docker compose rm -f "${CONTAINER_NAME}" - docker image prune -a -f + if ! run_docker_command_with_timeout docker compose stop --timeout "${CONTAINER_STOP_TIMEOUT_SECONDS}" "${CONTAINER_NAME}"; then + echo "โš ๏ธ Graceful stop failed or timed out. Force removing container: ${CONTAINER_NAME}" + if ! run_docker_command_with_timeout docker rm -f "${CONTAINER_NAME}"; then + echo "โŒ Failed to remove container: ${CONTAINER_NAME}" + return 1 + fi + elif ! run_docker_command_with_timeout docker compose rm -f "${CONTAINER_NAME}"; then + echo "โš ๏ธ Container removal failed or timed out. Force removing container: ${CONTAINER_NAME}" + if ! run_docker_command_with_timeout docker rm -f "${CONTAINER_NAME}"; then + echo "โŒ Failed to remove container: ${CONTAINER_NAME}" + return 1 + fi + fi + + if ! run_docker_command_with_timeout docker image prune -a -f; then + echo "โš ๏ธ Image cleanup failed or timed out. Continuing deployment." + fi }