Docker Exec
13. Docker Exec
Section titled “13. Docker Exec”💻 Accessing a Running Container
Section titled “💻 Accessing a Running Container”docker exec lets you run commands inside a running container without stopping it.
Analogy: It’s like SSH-ing into a running server to run commands.
🔧 Exec Commands
Section titled “🔧 Exec Commands”# Open an interactive bash shell inside a running containerdocker exec -it my-container bash
# If bash is not available (Alpine Linux), use shdocker exec -it my-container sh
# Run a one-off commanddocker exec my-container ls /app
# Run as a specific userdocker exec -u root -it my-container bash
# Set environment variable for the exec sessiondocker exec -e MY_VAR=hello -it my-container bash
# Run command in a specific directorydocker exec -w /app my-container ls🛠️ Real-World Exec Use Cases
Section titled “🛠️ Real-World Exec Use Cases”# Debug a Node.js containerdocker exec -it my-api sh> ls /app> node -v> cat package.json
# Access MongoDB shell inside containerdocker exec -it mongodb mongosh> show dbs> use myapp
# Access PostgreSQL inside containerdocker exec -it postgres-db psql -U postgres> \l> \c myapp
# Check environment variablesdocker exec my-container env
# Run database migrationdocker exec my-app node migrate.js
# View a config file inside a containerdocker exec nginx cat /etc/nginx/nginx.conf⚠️ Important Notes
Section titled “⚠️ Important Notes”docker execonly works on running containers- Changes made via
execare not persistent — they’re lost when the container is recreated - For permanent changes, update your Dockerfile