Scenario:
You have a container image myapp:grace built from /home/interview/Dockerfile that runs an application requiring cleanup on shutdown. When you run docker stop, the container is killed after the 10-second timeout instead of shutting down gracefully because the application doesn't properly handle the SIGTERM signal.
Task:
Fix the application script and Dockerfile to properly handle SIGTERM signals, implement cleanup logic, and ensure the container exits gracefully within 20 seconds when docker stop is executed.
Step 1: Test current container shutdown behavior
docker run -d --name test_grace myapp:grace
time docker stop test_grace
Should take ~10 seconds (default timeout) before force kill. Docker sends SIGTERM, waits, then sends SIGKILL.
Step 2: Check exit code and logs
docker inspect test_grace --format '{{.State.ExitCode}}'
docker logs test_grace
docker rm test_grace
Exit code 137 indicates SIGKILL (128 + 9). Logs should show no cleanup messages.
Step 3: Examine current configuration
cat /home/interview/Dockerfile
cat /home/interview/server.sh
Check if Dockerfile uses shell form vs exec form CMD, and if the script has signal handling (trap).
Step 4: Add signal handling to the application script
nano /home/interview/server.sh
Add trap to catch SIGTERM and perform cleanup:
#!/bin/sh
cleanup() {
echo "Received SIGTERM, cleaning up..."
sleep 2 # Simulate cleanup work
echo "Cleanup complete, exiting gracefully"
exit 0
}
trap cleanup TERM
echo "Application started"
while true; do
sleep 1
done
Step 5: Fix Dockerfile to use exec form
nano /home/interview/Dockerfile
Change from shell form to exec form. Shell form runs as /bin/sh -c "command" which doesn't forward signals. Exec form runs the command directly as PID 1:
# Before (shell form):
# CMD /app/server.sh
# After (exec form):
CMD ["/app/server.sh"]
Step 6: Rebuild the image
docker build -t myapp:grace .
Step 7: Test the fixed container
docker run -d --name test_fixed myapp:grace
sleep 3
time docker stop --timeout 20 test_fixed
Should exit quickly (within a few seconds) instead of waiting for timeout.