Essential Docker CLI Operations for Images and Containers
Docker containers operate as isolated micro-linux environments, each possessing its own network stack and IP address. The relationship between images and containers is foundational: an image is a static, read-only template (the filesystem), whereas a container is a running instance (the process) derived from that template. A single image can spawn multiple concurrent containers.
System-Level Utilities
docker version # Verify CLI and daemon versions
docker system info # Display system-wide information
docker --help # List available commands and flags
Image Operations
docker images # List locally available images
docker pull nginx:1.25 # Download a specific image from a registry
docker search python # Query the Docker Hub for images
docker image inspect <image_id> # Retrieve low-level image metadata
docker rmi <image_id> # Delete a specific image
docker rmi -f $(docker images -q) # Forcefully remove all local images
Container Lifecycle Maangement
# Running a container
docker run [options] <image_id_or_name>
# Options:
# -d : Run in detached mode (background)
# -it : Run interactively with a terminal
# -p <host>:<container>: Map host port to container port
# Example: Interactive Ubuntu shell
docker run -it ubuntu:latest /bin/bash
# Example: Background web server with port mapping
docker run -d -p 8080:80 nginx:latest
# Monitoring containers
docker ps # List active containers
docker ps -a # List all containers (active and stopped)
docker ps -n 3 # Show the 3 most recently created containers
docker ps -q # Output only container IDs
# Interacting with running containers
docker exec -it <cid> /bin/bash # Open a new terminal inside the container
docker attach <cid> # Attach to the primary process of the container
# Exiting an interactive session:
# exit : Terminate the container and exit
# Ctrl+P, Ctrl+Q : Detach from the container, leaving it running in the background
# State transitions
docker start <cid> # Start a stopped container
docker restart <cid> # Restart a running container
docker stop <cid> # Gracefully stop a container
docker kill <cid> # Forcefully terminate a container
# Removing containers
docker rm <cid> # Remove a stopped container
docker rm -f <cid> # Force remove a running container
docker rm -f $(docker ps -aq) # Force remove all containers
docker ps -aq | xargs docker rm # Alternative method to remove all stopped containers
# Diagnostics and File Operations
docker logs <cid> # Fetch container stdout/stderr logs
docker top <cid> # List running processes inside the container
docker inspect <cid> # Inspect container configuration and state
docker cp <cid>:/var/log/app.log ./app.log # Copy files from container to host
Persisting Container State
Modifications made inside a running container can be saved as a new image using the commit operation.
docker commit -m "Added custom modules" <container_id> custom_image_name:v1.0