Scenario
Docker
Intermediate
Build an Image with an Explicit Tag
Automate a local build with input checks and an explicit release tag.
The Situation
Docker automation with Bash
Task
Build the Dockerfile in a supplied directory and inspect the resulting image.
Save as build-image.sh. This script uses Bash.
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -ne 2 ]]; then
printf 'Usage: bash build-image.sh CONTEXT IMAGE:TAG\n' >&2
exit 2
fi
context_dir=$1
image_ref=$2
if [[ ! -f "$context_dir/Dockerfile" ]]; then
printf 'Dockerfile not found in the supplied context.\n' >&2
exit 2
fi
if [[ "$image_ref" == -* || "$image_ref" != *:* || "$image_ref" == *: ]]; then
printf 'Supply an image name with an explicit nonempty tag.\n' >&2
exit 2
fi
docker build --tag "$image_ref" -- "$context_dir"
docker image inspect --format '{{.Id}}' "$image_ref"
Run
From the custom-image lab directory:
bash build-image.sh . docker-lab-site:3
Docker performs full validation of the reference. The script’s check is a basic guard against accidentally omitting a tag.
Verify
A missing Dockerfile should return a nonzero exit status. A successful build should print the image ID.
Production Extension
Use a CI commit identifier as the tag, test the image, and record its registry digest after publication. Keep registry credentials in the CI secret store.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form