CMD vs ENTRYPOINT, exec vs shell form, and how do you get graceful shutdown in containers?
CMD vs ENTRYPOINT
ENTRYPOINTdefines the executable that always runs;CMDprovides default arguments (or a default command if there is no entrypoint).docker run image argsreplaces CMD but appends to ENTRYPOINT;--entrypointoverrides the entrypoint.- Typical pattern:
ENTRYPOINT ["java", "-jar", "app.jar"]withCMD ["--spring.profiles.active=prod"]as overridable defaults.
Exec vs shell form
- Exec form
["java", "-jar", "app.jar"]: the process runs directly as PID 1 and receives signals. - Shell form
java -jar app.jar: runs as/bin/sh -c "...". The shell is PID 1 and usually does not forward SIGTERM, so the JVM is killed with SIGKILL after the grace period, with no graceful shutdown. If a wrapper script is needed, end it withexec java ....
PID 1 responsibilities
PID 1 gets no default signal handlers and must reap zombie child processes. The JVM handles SIGTERM, but if the application spawns child processes, use a minimal init (docker run --init or tini).
Graceful shutdown for Spring Boot
- The orchestrator sends SIGTERM (Kubernetes also removes the pod from Service endpoints at the same time, asynchronously).
server.shutdown=gracefulstops accepting new requests and lets in-flight ones finish withinspring.lifecycle.timeout-per-shutdown-phase(for example 20 s); Kafka listeners stop and commit;@PreDestroyhooks run.- The orchestrator sends SIGKILL after the grace period (
terminationGracePeriodSeconds, default 30 s), so the application's timeout must be shorter. - In Kubernetes, add a short
preStopsleep (5–10 s) so load balancers stop sending traffic before the application starts refusing it.
Follow-up questions interviewers ask
Try answering each one before you open it.
What does a Docker HEALTHCHECK do and is it used by Kubernetes?
It runs a command periodically and marks the container healthy or unhealthy, which Docker and Compose use (for example depends_on: condition: service_healthy). Kubernetes ignores Dockerfile HEALTHCHECK and uses its own liveness, readiness and startup probes defined in the pod spec.