Skip to content

Exec and Logs

docker exec runs a new process inside an already-running container. The most common use is opening an interactive shell:

Terminal window
docker exec -it <container> sh
  • -i keeps stdin open (interactive)
  • -t allocates a pseudo-TTY (so you get a proper terminal prompt)
  • sh is the command to run (use bash if the image has it)

Inside the shell you can inspect files, run commands, and debug problems — exactly as if you were on the host machine.

Terminal window
# Example session
docker run -d --name webserver nginx:alpine
docker exec -it webserver sh
# Inside the container:
# / # cat /etc/os-release
# / # ls /usr/share/nginx/html
# / # exit

Every container writes its stdout/stderr to a log managed by Docker:

Terminal window
# Print all logs so far
docker logs webserver
# Follow (stream) new log lines in real time — like tail -f
docker logs -f webserver
# Show the last 20 lines
docker logs --tail 20 webserver
# Add timestamps
docker logs -t webserver

Logs are the first place to look when a container misbehaves. If a container keeps restarting, docker logs <name> usually tells you exactly why.

docker top lists the processes running inside a container — without entering it:

Terminal window
docker top webserver
UID PID PPID C STIME TTY TIME CMD
root 12345 12300 0 10:00 ? 00:00:00 nginx: master process nginx -g daemon off;
101 12346 12345 0 10:00 ? 00:00:00 nginx: worker process

You do not always need a full shell. docker exec can run any command directly:

Terminal window
# Check nginx config
docker exec webserver nginx -t
# View a file
docker exec webserver cat /etc/nginx/nginx.conf
# 1. Start nginx in the background
docker run -d --name webserver nginx:alpine

# 2. Check its logs
docker logs webserver

# 3. Run a one-off command inside it
docker exec webserver nginx -t

# 4. Open an interactive shell
#    (type 'exit' when done)
docker exec -it webserver sh

# 5. Watch processes
docker top webserver

# 6. Follow logs in real time (Ctrl+C to stop)
docker logs -f webserver
What does the -t flag do in 'docker exec -it container sh'?
Which command streams new log lines from a container in real time?
What happens to the container when you 'exit' the shell opened by docker exec?
Which command lists the processes running inside a container without opening a shell?