🐚 Get a Shell Inside Running Container
Need to debug inside container? docker exec runs commands. Interactive shell, one-off commands, scripts.
📝 Basic Exec Commands
# Get shell (bash for Linux, sh for Alpine) docker exec -it container_name /bin/bash docker exec -it container_name sh # Run single command docker exec container_name ls -la docker exec container_name cat /etc/hosts # Run as specific user docker exec -u root container_name whoami # Set working directory docker exec -w /app container_name ls # Set environment variable docker exec -e MY_VAR=value container_name printenv # Run in background (detached) docker exec -d container_name ./long-running-script.sh
🎯 Debugging with Exec
# Check processes docker exec container_name ps aux # Check logs inside container docker exec container_name tail -f /var/log/app.log # Test network connectivity docker exec container_name ping google.com docker exec container_name curl localhost:8080/health # Check environment variables docker exec container_name env # Install debugging tools (if package manager exists) docker exec -it container_name apt-get update docker exec -it container_name apt-get install -y curl vim # Copy file from container docker cp container_name:/app/config.json ./config.json
💡 Important Notes
- Container must be running (not exited)
- Use -it for interactive shell (without it, command runs and exits)
- Changes made inside container are lost if container restarts (unless volume)
- For production debugging, prefer logs over exec (security)
“App not working. docker exec -it container bash. Checked logs, found error. Fixed config, restarted. Debugged without redeploying. Docker exec is lifesaver.”

