Docker – Containers & Shells
Docker containers provide isolated environments for applications, but sometimes you need to interact with the container directly. Using shells, you can access a running container, execute commands, debug issues, and manage its environment effectively.
Accessing a Docker Container
To interact with a container, you can attach a shell session using docker exec or docker attach. This allows you to run commands inside the container as if you were logged into a standalone system.
Using docker exec
# Access container shell interactively
docker exec -it /bin/bash
# Run a command directly inside the container
docker exec ls /app
Using docker attach
# Attach to a running container's terminal
docker attach
# Detach without stopping the container (Press Ctrl + P, Ctrl + Q)
Checking Running Processes
You can list all processes running inside a container using ps or Docker-specific commands:
# List processes inside container
docker exec -it ps aux
# View container stats and resource usage
docker stats
Copying Files In and Out of Containers
Docker provides commands to copy files between host and container environments:
# Copy file from host to container
docker cp ./localfile.txt :/app/localfile.txt
# Copy file from container to host
docker cp :/app/file.txt ./file.txt
Inspecting Container Environment
You can inspect the container’s configuration, environment variables, and network settings using:
# View environment variables
docker exec -it printenv
# Inspect container details
docker inspect
Best Practices When Using Shells
- Use
docker execinstead ofdocker attachfor safer interactive sessions. - Do not make persistent changes inside containers; rebuild images for long-term changes.
- Use
docker logsto check application output instead of constantly accessing shells. - Keep containers minimal and secure; avoid installing unnecessary packages just for debugging.
- Detach safely from a container to avoid stopping it unintentionally.
Conclusion
Mastering Docker shells allows you to troubleshoot, debug, and manage running containers efficiently. This hands-on access is essential for developers and DevOps engineers to maintain containerized applications in production and development environments.
