Bash Scripts for Docker Automation
Docker is driven entirely from the command line: building images, starting and stopping containers, inspecting their state, reading their logs and cleaning up all happen through the docker command. That makes Bash a natural way to automate it. A deployment that is done by typing five docker commands by hand will sooner or later be done with a wrong port, a forgotten environment file or an old image; the same five commands in a script are run identically every time, and the script can check each step and react when one fails.
This lesson covers what makes docker commands reliable inside scripts: exit statuses, machine-readable output instead of the human tables, existence checks, and the difference between interactive and non-interactive use. It then shows common automation tasks, such as backing up a volume, and ends with a deployment script that replaces a running container with a new version and rolls back automatically when the new version is unhealthy.
The Test Setup
The examples were run with Docker Engine 29.9 on the test machine. That machine could not reach Docker Hub, so the images were built locally: a minimal base image demo/base:1.0 containing Bash, Dash and a few standard tools (created with docker import from a folder of files), and on top of it a tiny web application, demo/webapp, in three versions. Its whole program is a Bash loop around nc:
#!/bin/bash
# A tiny demo web app: answers every HTTP request with its version.
port=${PORT:-8080}
version=$(cat /app/VERSION)
echo "webapp $version listening on port $port"
trap 'echo "webapp: stopping"; exit 0' TERM
while :; do
body="webapp $version on $(hostname)"$'\n'
printf 'HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s' "${#body}" "$body" |
nc -l -N "$port" > /dev/null &
wait $!
done
FROM demo/base:1.0
COPY server.sh VERSION /app/
ENV PORT=8080
EXPOSE 8080
HEALTHCHECK --interval=5s --timeout=2s --start-period=2s --retries=2 \
CMD test ! -e /tmp/unhealthy && nc -z 127.0.0.1 8080
USER app
CMD ["/app/server.sh"]
The HEALTHCHECK instruction tells Docker to run a command inside the container every 5 seconds; the container counts as healthy while the command succeeds and unhealthy after two failures in a row (lesson 176 covers health checks in detail). Versions 1.0.0 and 1.1.0 are correct. Version 1.2.0 was built with PORT=9090, so it listens on the wrong port and its health check fails: a realistic stand-in for a broken release. The server waits for nc with wait $! instead of running it in the foreground, so that the TERM trap runs immediately when Docker stops the container (lesson 141).
Exit Statuses
docker run without --detach waits for the container to finish and exits with the container's exit status, so a script can use it like any other command. When the container cannot be started at all, Docker uses three statuses of its own, chosen to match the shell's conventions (lesson 116):
docker run --rm demo/base:1.0 sh -c 'exit 3'
docker run --rm demo/base:1.0 no-such-command
docker run --rm demo/base:1.0 /etc/passwd
docker run --rm --no-such-option demo/base:1.0 id
docker run --pull=never --rm demo/nothing:9 id
| Command | Status | Reason |
|---|---|---|
sh -c 'exit 3' | 3 | the container's own exit status |
no-such-command | 127 | the command was not found in the image |
/etc/passwd | 126 | the file exists but cannot be executed |
--no-such-option | 125 | an error in the docker command itself |
demo/nothing:9 | 125 | the image does not exist |
The messages for the last two:
unknown flag: --no-such-option
...
docker: Error response from daemon: No such image: demo/nothing:9
--pull=never stops docker run from trying to download a missing image; the default (missing) would contact the registry first. In a script, status 125 therefore means "Docker could not do what was asked", while any other non-zero status came from the program in the container.
Interactive Options in Scripts
-i keeps the container's standard input open, so data can be piped into it; -t gives the container a pseudo-terminal. People type docker run -it and docker exec -it out of habit, but in a script without a terminal, -t causes problems:
docker run --rm -it demo/base:1.0 id; echo "[status $?]"
docker run --rm -t demo/base:1.0 id -un | od -c | head -2
docker run --rm demo/base:1.0 id -un | od -c | head -2
echo hello | docker run --rm -i demo/base:1.0 cat
cannot attach stdin to a TTY-enabled container because stdin is not a terminal
[status 1]
0000000 r o o t \r \n
0000006
0000000 r o o t \n
0000005
hello
From cron or any script whose standard input is not a terminal, -it fails outright. -t alone works, but a terminal converts every line ending to \r\n, so captured output contains carriage returns that break comparisons such as [[ $user == root ]]. In scripts, use -i when data is piped in, and leave out -t.
Machine-Readable Output
The default output of docker ps and docker images is a table for people:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6e3921320a21 demo/webapp:1.0.0 "/app/server.sh" 11 seconds ago Up 10 seconds (healthy) 0.0.0.0:18080->8080/tcp web1
Column widths change with the content, and texts like "11 seconds ago" are not meant to be parsed. Docker offers three better tools.
--format with Go templates
--format takes a template in the Go template language, where {{.Field}} inserts a field. \t produces a tab, which makes the result easy to split with read or cut:
docker ps --format '{{.Names}}\t{{.Image}}\t{{.Status}}'
web1 demo/webapp:1.0.0 Up 10 seconds (healthy)
-q and --filter
-q prints only IDs, one per line, ready to pass to another command. --filter selects what is listed. Name filters are regular expressions that match anywhere in the name, so name=web would also match web10 and old-web; anchors make the match exact:
docker ps -q
docker ps -a --filter 'name=^web1$' --format '{{.ID}}'
6e3921320a21
6e3921320a21
docker inspect
docker inspect returns everything Docker knows about an object as JSON. With --format, a script picks single values; with jq (lesson 156), it can query the JSON freely:
docker inspect --format '{{.State.Status}} {{.State.Health.Status}} {{.Config.Image}} {{.RestartCount}}' web1
docker inspect web1 | jq -r '.[0] | "\(.Name) \(.State.StartedAt) \(.Config.Env | map(select(startswith("PORT="))) | .[0])"'
running healthy demo/webapp:1.0.0 0
/web1 2026-11-25T18:25:13.386859206Z PORT=8080
Checking Whether Something Exists
Scripts constantly need to know whether a container or an image exists. The reliable test is the exit status of docker container inspect or docker image inspect, with the output discarded:
docker image inspect demo/webapp:9.9 > /dev/null 2>&1; echo "image exists: $?"
docker container inspect web1 > /dev/null 2>&1; echo "container exists: $?"
docker container inspect web9; echo "[status $?]"
image exists: 1
container exists: 0
[]
Error response from daemon: No such container: web9
[status 1]
Both outputs must be discarded: for a missing object, Docker writes an empty JSON list [] to standard output and the error to standard error. Using the specific forms docker container inspect and docker image inspect matters, because plain docker inspect web1 would also succeed if an image, volume or network of that name existed.
Backing Up a Volume
A volume is storage that Docker manages and that outlives containers; databases and uploaded files usually live in volumes. Because a volume's location on the host is an internal detail, the portable way to back one up is to run a throwaway container that mounts both the volume and a host folder, and run tar inside it:
docker volume create appdata > /dev/null
docker run --rm -v appdata:/data demo/base:1.0 sh -c 'echo "order 1" > /data/orders.txt; mkdir -p /data/uploads; echo img > /data/uploads/a.png'
# back up: mount the volume read-only and a host folder, and run tar in a throwaway container
docker run --rm -v appdata:/data:ro -v /srv/t175/backups:/backup demo/base:1.0 \
tar -czf /backup/appdata-2026-11-25.tar.gz -C /data .
tar -tzf /srv/t175/backups/appdata-2026-11-25.tar.gz
# restore into a new volume
docker volume create appdata-restored > /dev/null
docker run --rm -v appdata-restored:/data -v /srv/t175/backups:/backup:ro demo/base:1.0 \
tar -xzf /backup/appdata-2026-11-25.tar.gz -C /data
docker run --rm -v appdata-restored:/data demo/base:1.0 cat /data/orders.txt
./
./orders.txt
./uploads/
./uploads/a.png
order 1
-v NAME:/path mounts a volume and -v /host/path:/path a host folder; :ro makes a mount read-only, so the backup cannot change the data it is copying. --rm deletes the helper container when it ends. The archive is created by root inside the container, so on the host it belongs to root. For a database, copying the files of a running server can produce an inconsistent backup; databases are backed up with their own dump tools instead, run through docker exec (lesson 200 builds such a script).
A Complete Example: Redeploy with Automatic Rollback
Deploying a new version of a containerized application by hand usually means: stop the old container, remove it, start a new one with the new image and the same options, and check that it works. Each step can go wrong, and if the new version does not work, the old one has already been deleted. redeploy.sh keeps the old container until the new one has proved itself healthy, and puts the old one back if it does not.
#!/usr/bin/env bash
#
# redeploy.sh - replace the running "webapp" container with a new image version,
# and roll back automatically if the new version is not healthy
#
# Usage: redeploy.sh [-p] [-w SECONDS] IMAGE:TAG
# -p pull the image from its registry first
# -w SECONDS how long to wait for the new container to become healthy (default: 30)
#
# The container's settings (name, port, environment file, volume) are fixed
# below, so that every deployment starts the container exactly the same way.
#
# Exit status: 0 deployed, 1 deployment failed (the previous version is running
# again if there was one), 2 usage error or another deployment running
set -uo pipefail
readonly NAME=webapp
readonly RUN_OPTS=(
--detach
--name "$NAME"
--restart unless-stopped
--publish 127.0.0.1:18080:8080
--env-file /srv/t175/webapp.env
--volume webapp-data:/data
--label deployed-by=redeploy.sh
)
pull=0 wait_secs=30
usage() { echo "usage: ${0##*/} [-p] [-w SECONDS] IMAGE:TAG" >&2; exit 2; }
log() { printf '%(%H:%M:%S)T %s\n' -1 "$*"; }
while getopts ':pw:' opt; do
case $opt in
p) pull=1 ;;
w) [[ $OPTARG =~ ^[0-9]+$ ]] || usage; wait_secs=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 1 )) || usage
image=$1
[[ ${image##*/} == *:* ]] || { echo "${0##*/}: give an explicit tag, e.g. myapp:1.4.2" >&2; exit 2; }
# Only one deployment at a time (lesson 171)
exec 9> "/run/lock/redeploy-$NAME.lock" || exit 2
flock -n 9 || { echo "${0##*/}: another deployment of $NAME is running" >&2; exit 2; }
exists() { docker container inspect "$1" > /dev/null 2>&1; }
# health NAME: prints healthy, unhealthy, starting, or "none" if the image
# has no HEALTHCHECK, or the container state (e.g. exited) if it is not running
health() {
docker container inspect --format \
'{{if ne .State.Status "running"}}{{.State.Status}}{{else if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' \
"$1" 2> /dev/null || echo missing
}
# wait_healthy NAME SECONDS: succeeds when the container is healthy (or running,
# for images without a health check) within SECONDS
wait_healthy() {
local name=$1 deadline=$(( EPOCHSECONDS + $2 )) state
while (( EPOCHSECONDS < deadline )); do
state=$(health "$name")
case $state in
healthy|none) return 0 ;;
starting) ;;
*) log "container state: $state"; return 1 ;;
esac
sleep 1
done
log "still not healthy after $2s (state: $(health "$name"))"
return 1
}
# --- 1. the image ---------------------------------------------------------------
if (( pull )); then
log "pulling $image"
docker pull --quiet "$image" > /dev/null || { log "pull failed"; exit 1; }
fi
docker image inspect "$image" > /dev/null 2>&1 || { log "image $image not found"; exit 1; }
# --- 2. move the current container aside (kept for a rollback) -----------------
old_image=''
if exists "$NAME"; then
old_image=$(docker container inspect --format '{{.Config.Image}}' "$NAME")
if [[ $old_image == "$image" ]]; then
log "$NAME already runs $image; nothing to do"
exit 0
fi
exists "$NAME-previous" && docker rm --force "$NAME-previous" > /dev/null
log "stopping $NAME ($old_image)"
docker stop --time 20 "$NAME" > /dev/null || exit 1
docker rename "$NAME" "$NAME-previous" || exit 1
fi
# --- 3. start the new version ------------------------------------------------------
log "starting $NAME ($image)"
if docker run "${RUN_OPTS[@]}" "$image" > /dev/null && wait_healthy "$NAME" "$wait_secs"; then
log "$NAME is healthy"
exists "$NAME-previous" && docker rm "$NAME-previous" > /dev/null
log "deployed $image"
exit 0
fi
# --- 4. roll back --------------------------------------------------------------------
log "new version failed; last lines of its log:"
docker logs --tail 5 "$NAME" 2>&1 | sed 's/^/ | /'
docker rm --force "$NAME" > /dev/null 2>&1
if [[ -n $old_image ]]; then
log "rolling back to $old_image"
docker rename "$NAME-previous" "$NAME" && docker start "$NAME" > /dev/null &&
wait_healthy "$NAME" "$wait_secs" && log "rollback complete: $NAME runs $old_image"
fi
exit 1
How It Works
- The run options live in one array.
RUN_OPTSholds every option the container is started with: name, restart policy, published port, environment file, volume and a label. Each deployment, and each rollback, therefore uses identical settings. An array keeps every option a separate word, however it is written (lesson 97). The port is published on127.0.0.1only, as is usual when a reverse proxy on the same host forwards traffic to it. - An explicit tag is required. Deploying
myappwithout a tag would meanmyapp:latest, which names a different image whenever someone pushes a new one; a deployment should always name an exact version. The test looks at the part after the last/(${image##*/}), so that a registry address with a port, such aslocalhost:5000/webapp, does not count as a tag. - One deployment at a time. A
flocklock (lesson 171) makes a second deployment of the same application fail immediately instead of interfering with the first. healthreads the state in one template. Go templates supportifandelse: the template prints the container status when it is not running (exited, for example), the health status when the image defines a health check, andnonewhen it does not. If the container does not exist,inspectfails and the function printsmissing.wait_healthypolls once per second until the container is healthy, gives up as soon as it is unhealthy or not running, and gives up at a deadline based on$EPOCHSECONDS. Images without a health check count as ready as soon as they run.- The old container is renamed, not removed.
docker stopthendocker rename webapp webapp-previousfrees the name for the new container while keeping the old one, with its configuration, ready to start again. A leftoverwebapp-previousfrom an earlier interrupted run is removed first. - Rollback. If the new container fails to start or does not become healthy, the script shows the last lines of its log, which usually explain the failure, removes it, renames the old container back and starts it.
- Messages carry timestamps, from
printf '%(%H:%M:%S)T', so the log shows how long each step took.
Running the Complete Example
The first deployment had no previous container; the second replaced version 1.0.0 with 1.1.0. After each one, curl asked the application for its version:
$ redeploy.sh demo/webapp:1.0.0
18:26:23 starting webapp (demo/webapp:1.0.0)
18:26:26 webapp is healthy
18:26:26 deployed demo/webapp:1.0.0
[status 0]
$ curl -s http://127.0.0.1:18080/
webapp 1.0.0 on a0082bc89f11
$ redeploy.sh demo/webapp:1.1.0
18:26:26 stopping webapp (demo/webapp:1.0.0)
18:26:26 starting webapp (demo/webapp:1.1.0)
18:26:28 webapp is healthy
18:26:28 deployed demo/webapp:1.1.0
[status 0]
$ curl -s http://127.0.0.1:18080/
webapp 1.1.0 on 827b1f0eca2e
The host name in the answer is the container ID, so it changes with every new container. Deploying the version that is already running does nothing:
$ redeploy.sh demo/webapp:1.1.0
18:26:28 webapp already runs demo/webapp:1.1.0; nothing to do
[status 0]
The broken version 1.2.0 listens on port 9090, so its health check fails. The script noticed after two failed checks, showed the log line that reveals the wrong port, and restored version 1.1.0:
$ redeploy.sh demo/webapp:1.2.0
18:26:28 stopping webapp (demo/webapp:1.1.0)
18:26:29 starting webapp (demo/webapp:1.2.0)
18:26:36 container state: unhealthy
18:26:36 new version failed; last lines of its log:
| webapp 1.2.0 listening on port 9090
18:26:36 rolling back to demo/webapp:1.1.0
18:26:38 rollback complete: webapp runs demo/webapp:1.1.0
[status 1]
$ curl -s http://127.0.0.1:18080/
webapp 1.1.0 on 827b1f0eca2e
$ docker ps -a --format '{{.Names}}\t{{.Image}}\t{{.Status}}'
webapp demo/webapp:1.1.0 Up 2 seconds (healthy)
The answer comes from the same container ID as before (827b1f0eca2e): the original 1.1.0 container was restarted, not recreated. The application was unavailable for about ten seconds in total, the price of stopping the old version before starting the new one on the same port. Avoiding even that requires running both versions side by side behind a load balancer or reverse proxy that switches between them.
A missing image is reported before anything is stopped. With -p, the script tries to download the image first; on the test machine, which could not reach the registry, docker pull failed and the script stopped there:
$ redeploy.sh demo/webapp:9.9.9
18:26:38 image demo/webapp:9.9.9 not found
[status 1]
$ redeploy.sh -p demo/webapp:9.9.9
18:26:38 pulling demo/webapp:9.9.9
18:26:39 pull failed
[status 1]
(docker pull also printed its own error message, about the unreachable registry, between those two lines.) Usage errors and a deployment started while another one is running exit with 2:
$ redeploy.sh demo/webapp
redeploy.sh: give an explicit tag, e.g. myapp:1.4.2
[status 2]
$ redeploy.sh localhost:5000/webapp
redeploy.sh: give an explicit tag, e.g. myapp:1.4.2
[status 2]
$ redeploy.sh -w x demo/webapp:1.0.0
usage: redeploy.sh [-p] [-w SECONDS] IMAGE:TAG
[status 2]
$ redeploy.sh demo/webapp:1.0.0 & sleep 0.5; redeploy.sh demo/webapp:1.0.0
18:26:39 stopping webapp (demo/webapp:1.1.0)
18:26:39 starting webapp (demo/webapp:1.0.0)
redeploy.sh: another deployment of webapp is running
[status 2]
18:26:41 webapp is healthy
18:26:41 deployed demo/webapp:1.0.0
Finally, docker inspect confirms that the container was started with the settings from RUN_OPTS: the variables from the environment file, the restart policy and the label:
docker inspect --format '{{.Config.Env}} {{.HostConfig.RestartPolicy.Name}} {{index .Config.Labels "deployed-by"}}' webapp
[APP_ENV=production LOG_LEVEL=info PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=8080] unless-stopped redeploy.sh
Old images accumulate with every deployment. Docker refuses to delete an image that a container still uses, which protects the running version and the rollback container:
$ docker rmi demo/webapp:1.0.0
Error response from daemon: conflict: unable to delete demo/webapp:1.0.0 (must be forced) - container 07af484a741f is using its referenced image 6d51f5e82821
[status 1]
Cleaning up unused images, stopped containers and build cache safely is the subject of the Docker cleanup project in lesson 201.