Docker CLI Commands Essentials
# CHAPTER 4
Docker CLI Commands Essentials
1. Introduction
To master Docker, you must master the command line. While graphical interfaces like Docker Desktop are helpful for visual overviews, professional DevOps engineers rely entirely on the Docker Command Line Interface (CLI) for speed, scripting, and automation. In this chapter, we will build your core Docker vocabulary, mastering the essential commands required to manage the lifecycle of images and containers daily.2. Learning Objectives
By the end of this chapter, you will be able to:-
View active and sleeping containers using
docker ps.
-
Retrieve application errors using
docker logs.
-
Gain terminal access inside a running container using
docker exec.
-
View the internal metadata of a container using
docker inspect.
-
Clean up unused resources using
docker rmanddocker rmi.
3. Beginner-Friendly Explanation
Imagine you are the manager of an office building (Your Computer).-
docker psis checking the security cameras to see exactly who is currently working in the office.
-
docker logsis reading a worker's notebook to see what they accomplished or if they wrote down any errors.
-
docker execis walking into a specific office room, tapping a worker on the shoulder, and asking them to perform a specific task right in front of you.
-
docker rmis firing a worker and clearing out their desk to make room for someone else.
4. Viewing Containers (docker ps)
The most frequently used command in Docker is ps (Process Status).
-
docker ps: Lists all currently running (alive) containers.
-
docker ps -a(or--all): Lists EVERY container, including the ones that have crashed, stopped, or gone to sleep.
The output will show you the Container ID, the Image used, when it was created, its current Status (e.g., Up 5 minutes or Exited (0)), and its mapped ports.
5. Managing Lifecycle (stop, start, rm)
Containers are designed to be spun up and destroyed rapidly.
-
Stop:
docker stop <containernameorid>(Sends a polite signal to the software to shut down gracefully. Takes ~10 seconds).
-
Kill:
docker kill <containernameorid>(Pulls the power plug instantly. The software crashes immediately).
-
Start:
docker start <containernameorid>(Wakes a sleeping container back up).
-
Remove Container:
docker rm <containernameorid>(Permanently deletes a stopped container from your hard drive).
-
Remove Image:
docker rmi <imagename>(Deletes the blueprint image to save disk space).
6. Peeking Inside (logs and inspect)
When a container crashes, you must investigate why.
-
Logs:
docker logs <containername>. This prints all the console output (likeconsole.log()in Node.js orprint()in Python) from the container.
-
*Pro tip:* Use
docker logs -f <containername>(-fmeans follow). The terminal will stay open and stream live logs in real-time as users hit your web server!
-
Inspect:
docker inspect <containername>. This spits out a massive JSON document detailing every low-level secret of the container, including its internal IP address, its mounted hard drives, and its environment variables.
7. Mini Project: Interacting Inside a Container
Let's launch a container and "break into" it to execute commands.Step-by-Step Tutorial:
-
1.
Open your terminal. Launch a detached Nginx container named
my-web:
- 2. Verify it is running:
- 3. Now, let's open an interactive terminal *inside* the isolated Linux container:
-
exec: Execute a command.
-
-it: Interactive Terminal (keeps the typing session open).
-
sh: The Shell program we want to run inside the container.
-
4.
Notice your terminal prompt changed! You are now inside the container. Type
ls /usr/share/nginx/html. You will see theindex.htmlfile that serves the Nginx welcome page.
-
5.
Type
exitto leave the container and return to your laptop's terminal.
- 6. Clean up:
8. Real-World Scenarios
A backend API container goes offline in production. The operations team immediately runsdocker ps -a to find the crashed container. They copy the Container ID and run docker logs <ID>. The logs reveal a "Database Connection Timeout" error. Without the CLI, finding this error would involve digging through server hard drives for hours.
9. Best Practices
- The System Prune: Over months of development, your computer will fill up with gigabytes of unused images, stopped containers, and abandoned networks. Once a month, run the ultimate cleanup command:
*Warning: This deletes EVERYTHING that is not currently running. It is a fantastic way to recover 20GB of hard drive space.*
10. Security Tips
-
Root Access via
exec: When you rundocker exec -it <container> bash, you are usually logged in as theroot(Admin) user inside that container. Be extremely careful when executing commands interactively in production containers, as you can accidentally delete critical application files.
11. Common Mistakes
-
Trying to
rma running container: If you typedocker rm my-webwhile the container is still "Up", Docker will throw an error:You cannot remove a running container. You mustdocker stopit first. *(Alternatively, you can force delete it withdocker rm -f my-web, but this is sloppy practice).*
12. Exercises
- 1. What command would you use to view the live, streaming console output of a Node.js container?
-
2.
Explain the function of the
-itflags when using thedocker execcommand.
13. FAQs
Q: Do I use the Container ID or the Container Name in CLI commands? A: You can use either! If the container name ismy-database and its ID is 9f8e7d6c, docker stop my-database and docker stop 9f8e will both work perfectly. (You only need to type the first 3 or 4 characters of the ID for Docker to recognize it).
14. Interview Questions
-
Q: A developer complains that their Docker container crashed immediately after starting, and now it does not appear when they type
docker ps. What CLI commands would you instruct them to use to locate the container and diagnose the crash?
-
Q: Differentiate between
docker stopanddocker kill. In what scenario would you be forced to usekilloverstop?
15. Summary
In Chapter 4, we built our fundamental Docker vocabulary. We mastered thedocker ps command to observe our container landscape, and utilized docker logs and docker inspect to extract vital troubleshooting data. Crucially, we learned how to penetrate an isolated container's perimeter using docker exec -it to gain interactive shell access. We concluded by practicing proper hygiene, stopping and removing our containers to keep our local environments clean.