3. Docker CLI Mastery: Essential Commands
Mastering the Docker Command Line Interface
The Docker CLI is your primary interface to containers, images, networks, and volumes. You will use these commands hundreds of times per week as a container engineer. This module covers every essential command with practical examples you can run immediately on your machine.
Container Lifecycle: From Creation to Deletion
Every container goes through a lifecycle: created, running, paused, stopped, and deleted. The `docker run` command combines `docker create` and `docker start` in one step — it creates a new container from an image and immediately starts it. When you run a container in the foreground (without `-d`), your terminal attaches to the container's standard output and standard error. Pressing Ctrl+C sends SIGTERM to the container, which should trigger graceful shutdown. The `docker stop` command sends SIGTERM, waits 10 seconds for graceful shutdown, then sends SIGKILL to force termination. `docker kill` sends SIGKILL immediately — use this when a container is unresponsive. The `docker ps` command shows running containers; add `-a` to show all containers including stopped ones. Stopped containers still consume disk space (their writable layer persists) — use `docker rm` to delete them. Adding `-f` forces removal of running containers, but prefer to stop gracefully first.
# Create and start a container in one command docker run -d --name webserver nginx:alpine # View running containers docker ps # View ALL containers (including stopped) docker ps -a # Stop a container gracefully (SIGTERM, 10s timeout) docker stop webserver # Start a stopped container docker start webserver # Force kill a container (SIGKILL, immediate) docker kill webserver # Remove a stopped container docker rm webserver # Force remove a running container (use with caution) docker rm -f webserver # Run a container that auto-removes when stopped (great for testing) docker run --rm -it alpine echo "This container deletes itself after exit"
Interactive Containers: Getting a Shell Inside
Sometimes you need to explore what's inside a container — inspect files, test commands, or debug configuration. The `-it` flags are essential for interactive containers: `-i` keeps STDIN open (so you can type input), and `-t` allocates a pseudo-TTY (so you get a proper shell prompt). Together, `-it` makes the container behave like a local terminal session. Running `docker run -it ubuntu bash` starts an Ubuntu container and drops you into a bash shell. Any commands you run inside — installing packages, creating files, editing configuration — affect ONLY this container's writable layer. When you exit the shell (with `exit` or Ctrl+D), the container stops unless you ran it with `-d`. To get a shell in an already-running container, use `docker exec -it container_name bash`. This is invaluable for debugging: you can exec into a container, check logs, examine environment variables, test network connectivity, and run diagnostic commands without stopping the container.
# Start an interactive Ubuntu container with bash # The --rm flag removes it when you exit docker run -it --rm ubuntu bash # Inside the container, you can run any Linux command root@container-id:/# apt update root@container-id:/# apt install -y curl root@container-id:/# curl http://example.com root@container-id:/# exit # For an already running container, exec into it docker run -d --name debug nginx docker exec -it debug bash # Now you can explore the running nginx container # Check environment variables inside a container docker exec debug env # Run a single command without interactive shell docker exec debug cat /etc/nginx/nginx.conf
Container Logs and Monitoring
Containers write their standard output and standard error to a logging driver (by default, the json-file driver). The `docker logs` command retrieves these logs. Without any flags, it prints all logs from the container's entire lifetime. In production, containers can generate gigabytes of logs, so you will almost always use flags: `--tail 100` shows only the last 100 lines, `-f` follows the logs in real-time (like `tail -f`), and `--since 1h` shows logs from the last hour. The `docker stats` command shows real-time resource usage for running containers — CPU percentage, memory usage and limit, network I/O, and block I/O. This is your first diagnostic tool when a container is behaving badly. If you see memory usage approaching the limit, the container may be leaking memory. If CPU is pegged at 100%, there may be an infinite loop or inefficient code. If network I/O is high, something is sending or receiving a lot of data.
# Run an nginx container that generates logs docker run -d --name logger nginx # Generate some access logs (make HTTP requests) curl http://localhost:8080 2>/dev/null # View container logs docker logs logger # Follow logs in real-time (Ctrl+C to stop) docker logs -f logger # Show last 50 lines only docker logs --tail 50 logger # Show logs from the last 30 minutes docker logs --since 30m logger # Monitor resource usage in real-time docker stats logger # Watch multiple containers docker stats container1 container2 container3
Working with Images: Pull, Push, List, and Remove
Images are the blueprints for containers. The `docker pull` command downloads an image from a registry (Docker Hub by default) without running it. This is useful when you want to pre-cache images or inspect them before use. The `docker images` command lists all images on your system, showing repository name, tag, image ID, creation time, and size. Image sizes shown are the compressed download size, not the expanded disk usage. The `docker tag` command creates an alias for an image — this is essential before pushing to a registry because the registry uses the tag to determine where to store the image. Tags follow the format `registry/repository:tag`. `docker push` uploads a tagged image to a registry. You must be logged in with `docker login` before pushing. The `docker rmi` command removes images, but will fail if any container (including stopped containers) uses that image. Use `docker image prune` to remove all unused images — dangling images (those with no tag and not used by any container) are removed first. Use `-a` to remove ALL unused images, not just dangling ones.
# Download an image without running it docker pull nginx:alpine # List all images on your system docker images # Show image history (layers) docker history nginx:alpine # Tag an image for a registry docker tag nginx:alpine myregistry.com/myapp:1.0.0 # Login to Docker Hub (or your private registry) docker login # Push to registry docker push myregistry.com/myapp:1.0.0 # Remove an image (fails if any container uses it) docker rmi nginx:alpine # Remove all unused images docker image prune # Remove ALL unused images (aggressive cleanup) docker image prune -a
Run `docker run -d --name test-nginx -p 8080:80 nginx:alpine`. Then open a browser to `http://localhost:8080` — you will see the Nginx welcome page. Run `docker logs test-nginx` to see access logs. Run `docker exec -it test-nginx sh` to get a shell inside. Run `docker stats test-nginx` to see resource usage. Finally, run `docker rm -f test-nginx` to clean up. This one exercise covers 80% of the commands you will use daily.
Knowledge Check
Ready to test your understanding of 3. Docker CLI Mastery: Essential Commands?