docker exec vs attach
Topic: Containers core
Summary
docker exec runs a new command in a running container. docker attach attaches to the main process stdin/stdout. Use exec for debugging or one-off commands; avoid attach for long-running or interactive processes. Use this when you need to run a command inside a container.
Intent: How-to
Quick answer
- docker exec -it container_id /bin/sh runs a new shell. Safe; does not affect main process. Use for debugging and one-off commands.
- docker attach container_id connects to main process. Ctrl+C can stop the container. Use only when you intend to interact with main process.
- Prefer exec. Use exec for cron, health checks, and ad-hoc commands. Attach only when you need to send input to main process.
Prerequisites
Steps
-
Use exec
docker exec -it mycontainer /bin/sh. Run any command. Exit with exit or Ctrl+D; container keeps running.
-
When to use attach
attach only when you need to interact with the main process. Beware Ctrl+C stopping container.
-
Best practice
Use exec for shells and one-off commands. Use attach only for intentional main-process interaction.
Summary
Use docker exec for new commands in a container; use attach only when interacting with the main process.
Prerequisites
Steps
Step 1: Use exec
Run docker exec -it container /bin/sh or any command; exit without stopping container.
Step 2: When to use attach
Use attach only when you need to talk to the main process; avoid Ctrl+C if you do not want to stop it.
Step 3: Best practice
Prefer exec for debugging and one-off tasks.
Verification
- exec runs command and exits; container still running. attach shows main process I/O.
Troubleshooting
No TTY — Use -it for interactive. Container exits on attach exit — That is normal for attach; use exec for shells.