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/shor/bin/bashgives 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:
-
Start the shell session:
docker exec -it CONTAINER_ID /bin/sh -
Navigate to the web server’s root directory:
cd /usr/share/nginx/html/ -
Modify a file (e.g., “hacking” the site):
echo "I hacked you!" > index.html -
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.