How to List Containers in Docker
Docker has revolutionized application development and deployment with its container technology, allowing developers to package applications with all dependencies into lightweight, portable units. As container usage grows in development and production environments, managing and monitoring these containers becomes increasingly crucial. One of the most fundamental Docker skills is the ability to list and view containers—this seemingly simple task provides vital visibility into your containerized environment.
This comprehensive guide explores everything you need to know about listing Docker containers, from basic commands to advanced filtering techniques, formatting options, and automation strategies. Whether you’re troubleshooting issues, monitoring performance, or performing regular maintenance, mastering these techniques will significantly enhance your Docker workflow.
Understanding Docker Containers and Why Listing Matters
What are Docker Containers and Their Role
Docker containers are standalone executable packages containing everything needed to run an application: code, runtime, libraries, environment variables, and configuration files. Unlike virtual machines, containers share the host system’s OS kernel, making them more efficient and faster to start.
Each container runs as an isolated process with its own filesystem, networking, and resource allocation. This isolation ensures consistent behavior across different environments, from development laptops to production servers.
Container states explained
Docker containers exist in various states throughout their lifecycle:
- Running: Container is currently executing processes
- Created: Container is created but not started
- Restarting: Container is in the process of restarting
- Exited: Container has completed its execution or been stopped
- Paused: Container processes have been temporarily paused
- Dead: Container the daemon tried and failed to stop
Understanding these states is essential for effective monitoring and management.
Why container listing is essential
Proper container listing and management capabilities offer numerous benefits:
- Monitoring active containers to ensure service availability
- Troubleshooting issues by identifying problematic containers
- Resource optimization by detecting resource-intensive containers
- Security auditing to check for unauthorized containers
- Cleanup operations to remove unused containers and reclaim storage
- Efficient cluster management in multi-container deployments
Basic Docker Container Listing Commands
The docker ps Command
The most fundamental command for listing Docker containers is docker ps
. When run without any options, it displays only currently running containers:
docker ps
This command provides essential information about each running container in a tabular format, showing Container ID, Image, Command, Created time, Status, Ports, and Names.
Understanding the output columns
When you run docker ps
, the output includes several important columns:
- Container ID: A unique alphanumeric identifier for each container
- Image: The template used to create the container
- Command: The instruction executed when Docker started the container
- Created: When the container was created
- Status: Whether the container is running, stopped, or in error
- Ports: Any port mappings for container networking
- Names: The identifying name (user-defined or randomly generated)
The docker container ls Command
As part of Docker’s newer command structure introduced in version 1.13, the docker container ls
command was introduced as an alternative to docker ps
:
docker container ls
Both commands provide identical functionality and accept the same options. The newer syntax follows Docker’s object-command structure, making it more consistent with other Docker commands.
Command aliases and compatibility
Docker provides several aliases for container listing:
docker ps
: The original, shorter command (still widely used)docker container ls
: The newer, more structured commanddocker container list
: Another alternative syntax
All these commands provide identical output and support the same options. Docker maintains backward compatibility while encouraging the newer syntax.
Listing All Docker Containers
Displaying Both Running and Stopped Containers
By default, docker ps
only shows running containers. To view all containers regardless of their state, use the -a
or --all
flag:
docker ps -a
Or with the newer syntax:
docker container ls -a
This command displays all containers on your system, including those that have stopped or exited, giving you a complete picture of your container landscape.
Viewing Recently Created Containers
To view only the most recently created containers, use the -n
or --last
option followed by the number of containers you want to see:
docker ps -n 5
This displays the five most recently created containers, regardless of their state.
To show only the newest container, use the -l
or --latest
option:
docker ps -l
Practical Examples
Here are some practical examples for specific scenarios:
Finding containers that exited with errors:
docker ps -a --filter "status=exited" --filter "exited=1"
Listing containers created from a specific image:
docker ps --filter "ancestor=nginx:latest"
Listing all running containers with file sizes:
docker ps -s
This adds a SIZE column that shows the amount of data written by each container in its writable layer, plus the virtual size of the container image (shown in parentheses).
Advanced Filtering Techniques
Using the –filter Option for Precise Results
The --filter
(or -f
) option allows you to filter containers based on specific criteria, making it powerful for environments with many containers:
docker ps --filter "key=value"
Filtering by Container Attributes
By status:
docker ps --filter "status=running"
Possible values include: running, created, restarting, exited, paused, and dead.
By name:
docker ps --filter "name=web-server"
By label:
docker ps --filter "label=environment=production"
By network:
docker ps --filter "network=bridge"
By volume:
docker ps --filter "volume=/data"
By port exposure:
docker ps --filter "publish=80"
Combining Multiple Filters
You can combine filters to create more specific queries:
docker ps --filter "status=exited" --filter "publish=80"
This command shows all stopped containers that published port 80 when they were running.
Another example:
docker ps --filter "label=app=web" --filter "network=frontend"
This lists containers with the label “app=web” connected to the “frontend” network.
Real-world Filtering Examples
Identifying resource-intensive containers:
docker ps --format "{{.ID}}: {{.Names}}" | xargs docker stats --no-stream
Finding containers from specific applications:
docker ps --filter "label=project=myapp"
Checking all containers on a specific network:
docker ps -a --filter "network=production-network"
Customizing Output Format
Using the –format Option with Go Templates
Docker allows customizing the output format using Go templates with the --format
option:
docker ps --format "{{.ID}}: {{.Names}}"
This gives you complete control over what information is displayed and how it’s formatted.
Practical Formatting Examples
Display only container IDs:
docker ps -q
This is particularly useful for scripting when you want to perform operations on multiple containers.
Create custom tables with selected columns:
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Image}}"
Format output as JSON:
docker ps --format "{{json .}}"
Display full command outputs without truncation:
docker ps --no-trunc
Size Information and Resource Usage
To display size information for each container, use the -s
or --size
flag:
docker ps -s
This adds a SIZE column showing:
- The size of data written by the container in its writable layer
- The virtual size (the container’s image size) shown in parentheses
Docker Compose Container Listing
Listing Containers in Docker Compose Projects
If you’re using Docker Compose to manage multi-container applications, you can list containers associated with your Compose project:
docker compose ps
This command, run from a directory containing a docker-compose.yml file, displays all containers defined in the Compose file along with their status.
Understanding Docker Compose Container Naming
Docker Compose uses a specific naming convention for containers: <project_name>_<service_name>_<index>
. The project name is typically the directory containing your docker-compose.yml file, the service name comes from service definitions in the file, and the index is a number that allows multiple instances of the same service.
Filtering and Managing Compose Containers
To identify containers from a specific Compose project using standard Docker commands:
docker ps --filter "label=com.docker.compose.project=myproject"
To list containers with specific status in a Compose project:
docker compose ps --filter "status=running"
Detailed Container Information
Using docker inspect for In-depth Details
For comprehensive information about a container, use the docker inspect
command:
docker inspect <container_id_or_name>
This returns detailed configuration and runtime information in JSON format, covering everything from basic configuration to networking settings, mounts, and current state.
Extracting Specific Container Information
You can extract specific information using the --format
option with Go templates:
docker inspect --format='{{.NetworkSettings.IPAddress}}' <container_id_or_name>
This example extracts only the container’s IP address.
Common Inspection Queries
Check container connectivity:
docker inspect --format='{{json .NetworkSettings.Networks}}' <container_id_or_name>
View mount points:
docker inspect --format='{{json .Mounts}}' <container_id_or_name>
Check environment variables:
docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' <container_id_or_name>
Practical Examples of Container Inspection
Debugging container issues:
docker inspect --format='{{json .State}}' <container_id_or_name>
This shows the container’s current state information, useful for troubleshooting startup or execution problems.
Auditing security settings:
docker inspect --format='{{json .HostConfig.SecurityOpt}}' <container_id_or_name>
Scripting and Automation
Integrating Container Listing in Shell Scripts
Container listing commands can be easily integrated into shell scripts for automation. Here’s a simple example that stops all running containers:
#!/bin/bash
docker ps -q | xargs -r docker stop
The -q
option returns only container IDs, which are then passed to the docker stop
command.
Processing Container IDs for Batch Operations
To perform actions on containers meeting specific criteria:
#!/bin/bash
# Stop all containers running the nginx image
docker ps -q --filter "ancestor=nginx" | xargs -r docker stop
Automation Examples
Scheduled cleanup of stopped containers:
#!/bin/bash
# Remove containers that exited more than 24 hours ago
docker ps -a --filter "status=exited" --format "{{.ID}} {{.CreatedAt}}" |
awk '$2 < "'$(date -d "24 hours ago" '+%Y-%m-%d')'T" {print $1}' |
xargs -r docker rm
Automatic resource usage monitoring:
#!/bin/bash
# Monitor container resource usage
docker ps -q | xargs docker stats --no-stream
Troubleshooting Container Listing Issues
Common Errors and Their Solutions
No output from docker ps
:
- Check if Docker daemon is running:
systemctl status docker
- Verify permissions to access Docker:
docker info
- Try running with sudo:
sudo docker ps
Permission denied errors:
- Add your user to the docker group:
sudo usermod -aG docker $USER
- Log out and back in for group changes to take effect
- Use sudo temporarily for Docker commands
API Connection Problems
If experiencing connection issues:
- Verify Docker daemon is running:
systemctl status docker
- Check Docker socket permissions:
ls -la /var/run/docker.sock
- Restart Docker service:
sudo systemctl restart docker
Performance with Many Containers
When managing numerous containers, commands might become slow. To improve performance:
- Use specific filters to reduce the result set
- Use the
-q
option when you only need container IDs - Consider container orchestration tools for large-scale deployments
Debugging Techniques
Check Docker daemon logs:
journalctl -u docker
Verify Docker client and server versions:
docker version
Incompatibilities between client and server versions can sometimes cause issues.
Best Practices for Container Management
Naming Conventions for Easier Listing and Filtering
Adopt a consistent naming convention instead of relying on Docker’s automatically generated names:
docker run --name env-service-number nginx
A good naming pattern might include:
- Environment (dev, test, prod)
- Service name (web, api, db)
- Instance number
This makes container identification and filtering much easier.
Effective Use of Labels for Organization
Labels provide a flexible way to add metadata to containers:
docker run -d --label environment=production --label app=web nginx
You can then filter containers based on these labels:
docker ps --filter "label=environment=production"
Regular Cleanup Strategies
Implement regular cleanup to avoid accumulating stopped containers:
# Remove all stopped containers
docker container prune
# Remove containers with specific age criteria
docker ps -a --filter "status=exited" --filter "since=24h" -q | xargs -r docker rm
Security Considerations When Listing Containers
- Restrict access to Docker commands using appropriate user permissions
- Be cautious about exposing container details in public environments
- Regularly audit container status to identify unauthorized containers
- Implement least privilege principles for container access
Container Listing in Different Environments
Docker Desktop vs. Server Environments
Docker Desktop (for Windows and Mac) and Docker Server (on Linux) offer the same container listing commands, but with some differences:
- Docker Desktop includes a GUI that visualizes containers
- Resource allocation differs between environments
- Volume mapping and networking have platform-specific behaviors
Cloud Provider Considerations
When working with Docker in cloud environments:
- Cloud providers might offer container-specific dashboards
- Provider-specific metadata might be available as labels
- Consider using managed container services for production workloads
Docker Swarm Specific Commands
In a Docker Swarm environment:
- Use
docker service ls
to list services - Services may have multiple container instances
- Filter containers by swarm labels:
docker ps --filter "label=com.docker.swarm.service.name=<service_name>"
Practical Cheat Sheet and Quick Reference
Essential Commands for Daily Use
- List running containers:
docker ps
- List all containers:
docker ps -a
- List container IDs only:
docker ps -q
- List most recent containers:
docker ps -n 5
- List containers with size info:
docker ps -s
Most Useful Filter Combinations
- Running containers for a specific app:
docker ps --filter "label=app=myapp"
- Containers with errors:
docker ps -a --filter "exited=1"
- Containers on a specific network:
docker ps --filter "network=frontend"
- Containers using a specific image:
docker ps --filter "ancestor=nginx:latest"
Common Formatting Patterns
- Custom table with selected fields:
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
- JSON output:
docker ps --format "{{json .}}"
- Names and IDs only:
docker ps --format "{{.Names}}: {{.ID}}"