0
0
Dockerdevops~5 mins

Why interacting with containers matters in Docker - Why It Works

Choose your learning style9 modes available
Introduction
Containers let you run apps in a small, isolated space. Interacting with containers helps you check if your app works, fix problems, and keep things running smoothly.
When you want to see if your app inside a container is running correctly.
When you need to look inside a container to fix a problem or change something.
When you want to stop or restart a container to apply updates or free resources.
When you want to check what containers are running on your system.
When you want to remove containers that you no longer need to save space.
Commands
This command lists all running containers so you can see what is active on your system.
Terminal
docker ps
Expected OutputExpected
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b1c2d3e4f5g6 nginx:1.23 "/docker-entrypoint.…" 10 minutes ago Up 10 minutes 0.0.0.0:8080->80/tcp my-nginx
-a - Show all containers, including stopped ones
This command opens a terminal inside the running container named 'my-nginx' so you can interact with it directly.
Terminal
docker exec -it my-nginx /bin/bash
Expected OutputExpected
root@b1c2d3e4f5g6:/#
-i - Keep STDIN open for interactive use
-t - Allocate a pseudo-TTY for terminal
This command stops the running container named 'my-nginx' to free resources or prepare for updates.
Terminal
docker stop my-nginx
Expected OutputExpected
my-nginx
This command removes the stopped container named 'my-nginx' to clean up your system.
Terminal
docker rm my-nginx
Expected OutputExpected
my-nginx
Key Concept

If you remember nothing else from this pattern, remember: interacting with containers lets you check, fix, and manage your apps easily.

Common Mistakes
Trying to exec into a container that is not running
The command fails because you can only open a terminal in running containers.
Use 'docker ps' to check if the container is running, and start it if needed before exec.
Removing a container without stopping it first
Docker will not remove a running container and will show an error.
Stop the container using 'docker stop' before removing it.
Not using -it flags when exec-ing into a container
Without these flags, you won't get an interactive terminal, making it hard to run commands inside.
Always use 'docker exec -it' to open an interactive shell.
Summary
Use 'docker ps' to see which containers are running.
Use 'docker exec -it <container>' to open a terminal inside a running container.
Use 'docker stop <container>' to stop a running container safely.
Use 'docker rm <container>' to remove a stopped container and clean up.