DevOps Scripting PatternsLesson 6.4
Bash scripts for Docker and Kubernetes automation
docker CLI in scripts, waiting for containers, kubectl in scripts, checking pod status, applying manifests, waiting for rollout, namespace operations, image tagging patterns, docker compose in CI
Docker Automation in Bash
Bash ties together Docker and Kubernetes CLI commands into repeatable workflows.
#!/usr/bin/env bash
set -euo pipefail
APP="myapp"
IMAGE_TAG="${REGISTRY}/${APP}:${VERSION}"
# Build and push
docker build \
--build-arg VERSION="$VERSION" \
--tag "$IMAGE_TAG" \
--cache-from "${REGISTRY}/${APP}:latest" \
.
docker push "$IMAGE_TAG"
docker tag "$IMAGE_TAG" "${REGISTRY}/${APP}:latest"
docker push "${REGISTRY}/${APP}:latest"Kubernetes Rollout
deploy_k8s() {
local namespace="$1" version="$2"
# Update the image
kubectl set image deployment/${APP} \
${APP}="${IMAGE_TAG}" \
-n "$namespace"
# Wait for rollout to complete (timeout: 5 min)
kubectl rollout status deployment/${APP} \
-n "$namespace" \
--timeout=300s
}
check_pods() {
local namespace="$1"
# Fail if any pod is not Running
local not_ready
not_ready=$(kubectl get pods -n "$namespace" \
--field-selector='status.phase!=Running' \
--no-headers | wc -l)
(( not_ready == 0 ))
}
deploy_k8s "production" "$VERSION"
check_pods "production"
echo "Deployment of $VERSION to production complete"Always use kubectl rollout status --timeout rather than manually polling pods. It exits non-zero on rollout failure, which integrates cleanly with set -e.
