Why Docker Container Won’t Quit with Ctrl + C (And How to Fix It)

When working with Docker, you might occasionally find that trying to stop a container using Ctrl + C just doesn’t work. It’s one of those little annoyances that can throw off your workflow. I ran into this issue recently and dug into what’s happening under the hood—and more importantly, how to fix it. Here’s what I found.

Thank me by sharing on Twitter 🙏

The Problem: Why Ctrl + C Isn’t Working

In most cases, when you hit Ctrl + C, it sends a SIGINT (interrupt) signal to the running process, which should gracefully shut down the container. However, not all processes inside the container are designed to handle this signal properly. Sometimes, the process inside might be a shell script, or there could be multiple layers of commands that don’t pass along the signal. The result? You end up pressing Ctrl + C repeatedly with no effect, getting more frustrated by the second.

The Fix: How to Make Ctrl + C Work as Expected

There are a few ways to ensure that your container respects the Ctrl + C command:

  1. Use the --init Option:
    Docker has a built-in option that runs a small init process inside your container, which handles signals properly and forwards them to your main process.
    • Note: --init is different from -i, which is short for --interactive
ShellScript
   docker run --init <your-image>

This is the quickest and easiest solution for most cases.

  1. Make Sure You’re Using Interactive and TTY Modes:
    When running containers interactively, always ensure you’re using both -t (pseudo-TTY) and -i (interactive) flags:
ShellScript
   docker run -it <your-image>

These flags help forward signals like Ctrl + C more effectively.

  1. Double-Check Your Entrypoint or Command:
    If your container runs a script or some other command as its entry point, it’s important to use exec to ensure signals are handled correctly. For example, if you have a shell script as your entry point, the script should look like this:
ShellScript
   #!/bin/sh
   exec your-command

Using exec replaces the shell with your intended command, making sure signals like SIGINT get passed along.

  1. Customize the Stop Signal:
    If you need more control, you can specify the stop signal Docker should use with the --stop-signal option:
ShellScript
   docker run --stop-signal SIGINT <your-image>

This is useful in cases where you need to override the default stop behavior.

Wrapping Up: Smoothly Shutting Down Your Docker Containers

It’s easy to overlook signal handling when running containers, but it’s crucial for ensuring your applications shut down smoothly. By tweaking a few settings—like adding the --init flag or adjusting your entrypoint—you can avoid the frustration of unresponsive containers. Next time you hit Ctrl + C, you’ll know exactly what to do if it doesn’t work as expected.

Share this:

Leave a Reply