9.4.4.5 Exec Interactive Mode
A focused guide to Exec Interactive Mode, connecting core concepts with practical Docker and container operations.
Exec interactive mode refers to running docker compose exec with both standard input attached and a pseudo-terminal allocated, the combination that makes a genuinely interactive session — like a shell or a database client's interactive prompt — actually usable, as opposed to a single, non-interactive command execution.
Why Interactive Mode Is the Default for Exec
Unlike docker run, where interactivity requires explicit flags, docker compose exec allocates a pseudo-terminal and attaches standard input by default, making most interactive use cases work without needing to think about this explicitly.
docker compose exec api sh
This default behavior is exactly what makes an interactive shell session like this one usable at all, with proper terminal handling for things like command history and text editing within the shell.
Explicitly Disabling Interactivity When Not Needed
For a non-interactive, single command being run as part of a script, disabling the pseudo-terminal allocation can avoid unnecessary overhead or unexpected terminal-related behavior.
docker compose exec -T api npm run lint
The -T flag disables pseudo-terminal allocation, more appropriate when the command's output is being captured or processed programmatically rather than viewed interactively.
Why This Matters for Scripted Usage
A script piping exec's output to another command, or capturing it into a variable, generally benefits from disabling pseudo-terminal allocation, since interactive terminal behavior can introduce unwanted formatting or behavior in a non-interactive context.
RESULT=$(docker compose exec -T api npm run check 2>&1)
Why Exec Interactive Mode Matters
Understanding when interactive mode is appropriate (genuinely interactive sessions like shells) versus when it should be explicitly disabled (scripted, non-interactive command execution) ensures exec behaves correctly and predictably across both kinds of usage.