Interactive Shell

Being able to run one-off commands with docker exec is nice, but it’s often more convenient to start an active shell session running within the container itself.

The -i and -t Flags

To get an interactive shell, you use the -i and -t flags with exec:

  • -i (interactive): Keeps STDIN open even if not attached.
  • -t (tty): Allocates a pseudo-TTY (gives us a keyboard interface).
  • Running /bin/sh or /bin/bash gives us a shell session inside the container.

Starting a Shell Session

docker exec -it CONTAINER_ID /bin/sh

Example: Modifying Files Interactively

Once inside the shell, you can navigate and modify files just like you would on any Linux system. For example, if you are running an Nginx container:

  1. Start the shell session:

    docker exec -it CONTAINER_ID /bin/sh
  2. Navigate to the web server’s root directory:

    cd /usr/share/nginx/html/
  3. Modify a file (e.g., “hacking” the site):

    echo "I hacked you!" > index.html
  4. When you are done, you can exit the container shell session:

    exit

This is incredibly useful for debugging or exploring the environment of a running container.