🎓 A1Learner
🔍
0 of 50 lessons completed

Run Commands Inside a Container

docker exec runs a command inside a running container. The -it flags give the command a terminal, so a shell inside the container feels like a shell on the machine.

Read the container's release file

This command reads the operating system name inside the container.

docker exec g3-web cat /etc/os-release | head -1

Open a shell inside

The -it flags open an interactive shell in the container.

docker exec -it g3-web sh

Example

docker run -d --name g3-web nginx:1.27-alpine >/dev/null
docker exec g3-web cat /etc/os-release | head -1
docker exec g3-web ls /usr/share/nginx/html

Key points

  • Use docker exec to run a command in a running container.
  • Use -it for an interactive shell inside the container.
  • The shell runs as the container's user, inside its files.
  • Use exit to leave the shell. The container keeps running.
  • Use docker exec without -it for one-shot commands, like cat or ls.

In this example, Docker starts nginx and runs two commands inside it. The first reads the container's operating system release. The second lists the web files nginx serves. Both answers come from inside the container, not from the host.

Note

exec needs a running container. A stopped container cannot run a command.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does docker exec -it do?