Exec and Logs
Opening a shell in a running container
Section titled “Opening a shell in a running container”docker exec runs a new process inside an already-running container. The most common use is opening an interactive shell:
docker exec -it <container> sh-ikeeps stdin open (interactive)-tallocates a pseudo-TTY (so you get a proper terminal prompt)shis the command to run (usebashif 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.
# Example sessiondocker run -d --name webserver nginx:alpinedocker exec -it webserver sh
# Inside the container:# / # cat /etc/os-release# / # ls /usr/share/nginx/html# / # exitViewing container logs
Section titled “Viewing container logs”Every container writes its stdout/stderr to a log managed by Docker:
# Print all logs so fardocker logs webserver
# Follow (stream) new log lines in real time — like tail -fdocker logs -f webserver
# Show the last 20 linesdocker logs --tail 20 webserver
# Add timestampsdocker logs -t webserverLogs are the first place to look when a container misbehaves. If a container keeps restarting, docker logs <name> usually tells you exactly why.
Inspecting processes with docker top
Section titled “Inspecting processes with docker top”docker top lists the processes running inside a container — without entering it:
docker top webserverUID PID PPID C STIME TTY TIME CMDroot 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 processRunning one-off commands
Section titled “Running one-off commands”You do not always need a full shell. docker exec can run any command directly:
# Check nginx configdocker exec webserver nginx -t
# View a filedocker 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