Scenario Docker Intermediate

Check a Container's Web Response

Combine container state with an HTTP check in a Bash script.

1 min read
3 Steps
2 Services Used
~30 min Duration
Intermediate Difficulty
The Situation

Docker automation with Bash

Task

Check that a named container is running and that a supplied HTTP endpoint responds successfully. Requires Bash, Docker, and curl.

Save as check-web.sh:

#!/usr/bin/env bash
set -euo pipefail

if [[ $# -ne 2 ]]; then
    printf 'Usage: bash check-web.sh CONTAINER HTTP_URL\n' >&2
    exit 2
fi

container_name=$1
endpoint=$2
if [[ "$container_name" == -* ]]; then
    printf 'Invalid container name.\n' >&2
    exit 2
fi

running=$(docker inspect --type container --format '{{.State.Running}}' "$container_name")
if [[ "$running" != true ]]; then
    printf 'Container is not running.\n' >&2
    exit 1
fi

curl --fail --silent --show-error --max-time 10 --output /dev/null -- "$endpoint"
printf 'Container is running and the endpoint responded successfully.\n'

Run

Start the first web lab, then:

bash check-web.sh docker-lab-web http://127.0.0.1:8090

Verify Failure

Stop the lab container and rerun the script. Expect a nonzero result. Also test an incorrect port while the container is running.

Limitations

This checks the endpoint supplied by the caller; it cannot prove the response came from the named container. A generic HTTP success does not prove database readiness or business correctness. Use an application-specific health endpoint for stronger checks.


Docker Roadmap

Services Used
DockerBash

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form