The Analogy: A Pushback Tug Handing an Aircraft Over to Its Own Engines
An airliner at the gate cannot begin its journey unaided. Before it can taxi it needs work done for it from outside: ground power while its engines are cold, fuel from the bowser, and a push back off the stand because it cannot reverse under its own thrust. A tug and a ground crew perform all of this while the aircraft's own systems wait, dormant and dependent. This is exactly the role of a container entrypoint script. The application inside the image should not be cluttered with setup it has no business doing at startup: reading environment defaults, waiting for the database to accept connections, applying migrations, rendering a config file from templates. The entrypoint is the ground crew that does that preparation first, in a fixed order, before the real process is allowed to come alive.
The decisive moment is the handoff. Once the pushback is complete, the tug does not stay coupled to the nose gear and drive alongside; it disconnects completely and clears away, and the aircraft proceeds under its own engines, now in direct contact with the control tower. The tug removes itself from the chain of command entirely. In an entrypoint that clean disconnect is the single line exec "$@". Instead of the setup shell launching the application as a child and lingering as its parent, "exec" makes the shell replace itself with the application. The process the shell was becomes the application, inheriting its process identity -- in a container, that means the app becomes PID 1 and talks to Docker directly, exactly as the airborne aircraft talks straight to the tower.
Why the disconnect must be total becomes clear the moment the tower issues an instruction. A "hold position" or "return to gate" has to reach whoever is actually flying the aircraft. If the tug were still coupled and nominally in charge, every instruction would have to be relayed through the tug driver, and anything the driver failed to pass on would simply never happen. Signals work the same way. When you run "docker stop", Docker sends SIGTERM to PID 1. If the entrypoint shell is still PID 1 because it launched the app as a child rather than exec-ing it, that SIGTERM lands on the shell -- which, by default, does not forward it to the child. The application never hears the polite request to shut down.
The failure mode, then, is the tug that never fully disconnects. The tower calls "return to gate", the message dies with the tug driver, the aircraft rolls on oblivious, and after a fixed timeout the ramp gives up on courtesy and orders an emergency all-stop -- the abrupt SIGKILL that Docker sends when the stop timeout expires, cutting power mid-motion and risking a bad state on disk. A second, quieter failure is pushing an aircraft back with no flight plan filed at all: the crew completes every step, the tug disconnects, and the aircraft simply sits on the apron with its engines idling, going nowhere, while the paperwork says it departed. That is the entrypoint that runs "exec" with an empty command -- all the setup succeeds, nothing is actually started, and the container reports success while doing nothing.
Syntax or Core Structure
Every well-formed entrypoint follows the same three-beat shape: apply defaults, do the setup, then hand off with "exec". The skeleton below reads two settings from the environment (falling back to sensible defaults), prints what it resolved, and then replaces itself with whatever command the container was told to run. The "$@" carries every argument through untouched, and the quotes around it preserve arguments that contain spaces.
#!/usr/bin/env bash
set -e
# apply defaults from the environment
: "${APP_ENV:=production}"
: "${APP_PORT:=8080}"
echo "starting in $APP_ENV on port $APP_PORT"
# hand off to the container's command as PID 1
exec "$@"
Output:
starting in staging on port 8080
hello from app
That output comes from running the script as "APP_ENV=staging entrypoint.sh echo 'hello from app'". "APP_ENV" was supplied, so it stays "staging"; "APP_PORT" was not, so the ":=" assignment fills in "8080". The ":" builtin is a no-op whose only job here is to give "${VAR:=default}" a harmless command to sit in, so the assignment happens without printing or running anything. Then "exec echo 'hello from app'" replaces the shell entirely -- the "echo" is not a child of the script, it is the script's process now, which is precisely why the second line of output appears and why the container's signals will reach it directly.
Technical Depth: The Handoff and the Environment
exec and PID 1: the Signal Problem
"exec" does not run a command and wait for it; it abandons the current process image and becomes that command. Anything written after an "exec" line is unreachable, and that unreachability is the proof that the replacement happened:
#!/usr/bin/env bash
echo "before exec"
exec echo "the exec'd command"
echo "after exec (never printed)"
Output:
before exec
the exec'd command
The third "echo" never runs because there is no shell left to run it. Now transfer that to a container. Docker sends lifecycle signals -- SIGTERM on "docker stop", then SIGKILL after a grace period -- to PID 1 only. Whichever process is PID 1 must be the one that should react. The table shows how the common handoff styles differ:
| Handoff style | Ends up as PID 1 | Gets SIGTERM on docker stop |
|---|---|---|
exec "$@" | the application itself | yes, directly -- clean shutdown |
"$@" as a child | the entrypoint shell | no; the shell must trap and relay it |
"$@" & then wait | the shell, app in background | shell gets it; needs a trap to forward |
Only the first style gives the application the signals for free. The other two leave the shell sitting as PID 1, and a plain shell does not pass SIGTERM to its children, so the app runs on until the SIGKILL deadline and dies mid-work. If you genuinely cannot "exec" (you have real cleanup to do first), you must install a "trap" that forwards the signal by hand -- but "exec" is the simpler and safer default.
Environment Defaults: :- versus := versus :?
Entrypoints live or die by how they read the environment, and bash offers three distinct fallback operators that beginners routinely confuse. ${VAR:-default} yields the default but leaves "VAR" untouched; ${VAR:=default} yields the default and assigns it so later references see it; ${VAR:?message} aborts with an error if "VAR" is empty or unset, which is how you make a variable mandatory. The demo makes the difference concrete:
#!/usr/bin/env bash
unset REGION
printf 'default only: %s\n' "${REGION:-us-east}"
printf 'still unset: %s\n' "${REGION:-<none>}"
: "${REGION:=eu-west}"
printf 'now assigned: %s\n' "$REGION"
Output:
default only: us-east
still unset: <none>
now assigned: eu-west
The first line uses ":-" and prints "us-east", but the second line proves "REGION" is still unset -- ":-" never wrote anything back. Only after the ":=" line, which assigns as a side effect, does the bare "$REGION" hold "eu-west". The practical rule for entrypoints: use ":=" for defaults the rest of the script and the app will read, ":-" for a one-off fallback you do not want to persist, and ":?" for a required secret like a database password, so the container fails loudly at startup instead of connecting with an empty string.
Real World Example: A Production Entrypoint
A real service entrypoint does more than a bare "exec". It resolves configuration, waits for the things it depends on, optionally runs a one-time init, and only then starts the app -- logging each step so a failed startup is legible in the container logs. The script below is a representative shape: it applies defaults, polls a dependency with a bounded retry, conditionally runs migrations, and hands off.
#!/usr/bin/env bash
set -euo pipefail
: "${APP_ENV:=production}"
: "${DB_HOST:=db}"
: "${RUN_MIGRATIONS:=false}"
log() { printf '[entrypoint] %s\n' "$1"; }
check_db() { [ "$DB_HOST" = "db" ]; }
wait_for_db() {
local attempt=1 max=5
while [ "$attempt" -le "$max" ]; do
if check_db; then
log "database reachable on attempt $attempt"
return 0
fi
log "waiting for database (attempt $attempt)"
attempt=$((attempt + 1))
done
log "database unreachable after $max attempts"
return 1
}
log "environment: $APP_ENV"
wait_for_db
if [ "$RUN_MIGRATIONS" = "true" ]; then
log "applying migrations"
else
log "skipping migrations"
fi
log "handing off to: $*"
exec "$@"
Output:
[entrypoint] environment: production
[entrypoint] database reachable on attempt 1
[entrypoint] applying migrations
[entrypoint] handing off to: echo app started
app started
That output is from "RUN_MIGRATIONS=true entrypoint.sh echo 'app started'". "APP_ENV" and "DB_HOST" take their defaults, so the log reads "production" and the check passes on the first attempt. "RUN_MIGRATIONS" was set to "true", so the migration branch runs. The final log line echoes the command about to take over, and then "exec" replaces the shell with "echo app started", whose output is the last line. Every line is prefixed, ordered, and free of timestamps, so the same inputs always produce the same log.
The structure teaches the good habits. Setup is a sequence of small, named functions; each phase logs a human-readable line; the dependency wait is bounded by "max" attempts rather than looping forever; and the whole thing ends in "exec" so the app inherits PID 1. The bounded retry is important on its own: an unbounded "wait for the database" is the classic reason a container hangs in "starting" forever when its dependency is genuinely gone.
But the script is a teaching stand-in, and its most dangerous flaw is the migration step. Running migrations from the entrypoint means every container runs them on startup -- and when you scale to several replicas, they all try to migrate the same database at once, a race that can deadlock or half-apply a schema. Migrations belong in a single init job or behind a lock, not in code that every replica executes. The other limits compound that. "check_db" is a placeholder for a real probe; a genuine one would test an actual TCP connection, and the portable ways to do that ("nc -z", or bash's "/dev/tcp") are themselves environment-dependent -- "/dev/tcp" is a bashism absent from dash. The retry loop has no delay between attempts, so against a truly slow dependency it would spin uselessly; a real one needs a "sleep" with backoff, which I omitted only to keep this output deterministic. And there is no guard for an empty command: if the container is started with no arguments, "$@" is empty, "exec" does nothing, and the script exits 0 having started nothing at all -- the aircraft pushed back with no flight plan. A production version would add [ "$#" -gt 0 ] || { log "no command given"; exit 2; } before the handoff.
Common Mistakes
- Forgetting "exec" before the command. Launching the app as a child leaves the shell as PID 1, so "docker stop" hits the shell, the app never gets SIGTERM, and shutdown drags out until the SIGKILL deadline. Almost every entrypoint should end in "exec".
- Leaving "$@" unquoted. Writing
exec $@word-splits the arguments, so a command argument containing a space is torn into two. Alwaysexec "$@"so each argument is passed through intact.
- Running migrations in the entrypoint. With more than one replica, every container migrates the same database on startup at once -- a race that can deadlock or partially apply a schema. Migrations belong in a single init job or behind a lock.
- An unbounded dependency wait. A "while true" loop that waits forever for the database means that if the database is genuinely gone, the container hangs in "starting" indefinitely instead of failing. Bound the retries and exit non-zero when they are exhausted.
- Confusing "${VAR:-x}" with "${VAR:=x}". The ":-" form yields a default but does not assign it, so a later reference to the bare variable is still empty. Use ":=" when the rest of the script or the app must see the value.
- No guard for an empty command. If "$@" is empty, "exec" silently does nothing and the container exits 0 having started no process. Check "$#" before the handoff and fail loudly when there is nothing to run.
- Skipping "set -euo pipefail". Without it, a failed setup step -- a migration that errored, a config render that produced nothing -- is ignored, and the app starts in a broken environment. Make setup failures fatal.
- Doing build-time work at startup. Installing packages or compiling assets in the entrypoint makes every container start slow and non-reproducible. Anything that does not depend on runtime configuration belongs in the image build, not the entrypoint.
- Handing off as root. If the entrypoint runs as root and execs the app as root, a compromise of the app is a compromise of the container's full privileges. Drop to an unprivileged user before the handoff (for example via a "USER" directive or a privilege-dropping exec).
Best Practices
- End the entrypoint with "exec". Replace the shell with the application so it becomes PID 1 and receives Docker's signals directly, giving you graceful shutdown for free.
- Always quote the forwarded arguments. Write
exec "$@"so arguments containing spaces survive the handoff as single words.
- Use ":=" for defaults and ":?" for requirements. Assign persistent defaults with
${VAR:=value}, and make mandatory secrets fail loudly at startup with${VAR:?message}rather than connecting with an empty value.
- Turn on strict mode. Begin with "set -euo pipefail" so a failed migration or config step aborts startup instead of launching the app into a broken environment.
- Bound every dependency wait. Cap retries and exit non-zero when they are exhausted, so a missing dependency fails the container instead of hanging it in "starting" forever.
- Keep migrations off the per-replica path. Run schema changes once, from a dedicated init job or behind a lock, never from code that every replica executes on boot.
- Make startup legible. Emit one clear, prefixed log line per phase to stdout or stderr so a failed boot can be diagnosed from "docker logs" alone.
- Prefer build time and least privilege. Bake reproducible setup into the image rather than the entrypoint, and hand off to an unprivileged user so a compromised app does not inherit root.
Practice Exercises
- Add a graceful-shutdown path. Write an entrypoint that has real cleanup to do and therefore cannot use "exec": start the app in the background, install a "trap" on SIGTERM that forwards the signal to the child and then "wait"s for it, and demonstrate that the child receives the signal and exits cleanly.
- Make a secret mandatory. Take an entrypoint that reads
${DB_PASSWORD:-}and change it to${DB_PASSWORD:?DB_PASSWORD is required}. Show that with the variable unset the container aborts immediately with the message, and with it set the startup proceeds.
- Guard the empty command. Add
[ "$#" -gt 0 ]protection to the Real World Example entrypoint so that starting it with no command exits 2 with a clear message. Demonstrate both the guarded failure and a normal run that still hands off correctly.
- Move migrations behind a flag. Refactor the entrypoint so migrations run only when a "LEADER=true" variable is set, simulating a single designated init container. Run it twice -- once as the leader and once not -- and show that only the leader applies migrations while both start the app.