Tech Interview RoomStudy guides

Docker

CMD vs ENTRYPOINT, exec vs shell form, and how do you get graceful shutdown in containers?

Intermediate · 2 min read · Lesson 3 of 6 in Docker

CMD vs ENTRYPOINT

  • ENTRYPOINT defines the executable that always runs; CMD provides default arguments (or a default command if there is no entrypoint).
  • docker run image args replaces CMD but appends to ENTRYPOINT; --entrypoint overrides the entrypoint.
  • Typical pattern: ENTRYPOINT ["java", "-jar", "app.jar"] with CMD ["--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 with exec 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

  1. The orchestrator sends SIGTERM (Kubernetes also removes the pod from Service endpoints at the same time, asynchronously).
  2. server.shutdown=graceful stops accepting new requests and lets in-flight ones finish within spring.lifecycle.timeout-per-shutdown-phase (for example 20 s); Kafka listeners stop and commit; @PreDestroy hooks run.
  3. The orchestrator sends SIGKILL after the grace period (terminationGracePeriodSeconds, default 30 s), so the application's timeout must be shorter.
  4. In Kubernetes, add a short preStop sleep (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.