Sorting the output of docker ps can be helpful when you’re managing multiple containers and need a clearer view of what’s running. In this tutorial, we’ll walk through creating a Bash function that organizes this output in a more readable way using built-in shell tools like awk and sort. This builds upon Docker basic commands like docker ps, docker images, and docker inspect to create more powerful container management tools.
Software Requirements and Linux Command Line Conventions
Software Requirements and Linux Command Line Conventions
Category
Requirements, Conventions, or Software Version Used
System
Linux (any distribution with Docker installed)
Software
Docker, Bash Shell, awk
Other
Text editor (e.g., nano, vim)
Conventions
# – Run as root or with sudo $ – Run as a regular user
Bash Functions to Sort Docker PS Output
DID YOU KNOW?
You can combine docker ps with Bash to filter, sort, and monitor your containers more effectively? For example, you can list only the newest containers, find those that have exited, or even create custom views by name or uptime. It’s a great way to stay in control when managing lots of containers!
Step-by-Step Instructions
What These Functions Do
These bash functions solve common Docker container management challenges:
docker_ps_sort – Alphabetically sorts your running containers by name while maintaining the table format. This helps you quickly locate specific containers in environments with many services.
docker_ps_sort_image – Sorts containers by image name, making it easy to identify all containers running the same image version. This is particularly useful for version control and update planning.
Below are the steps to create, apply, and test improved Bash functions for sorting docker ps output while maintaining proper table formatting.
Create the Bash FunctionOpen your shell profile file (e.g., ~/.bashrc or ~/.bash_aliases) and add the following improved function:
What this function does: The docker_ps_uptime function sorts containers by how long they’ve been running, showing the newest containers at the top. This is particularly useful when troubleshooting recently deployed containers or when you need to identify which containers might have restarted unexpectedly.
Make It PermanentEnsure the functions are loaded in every session by keeping them in your shell configuration file. You can create a dedicated file for Docker functions:
# In ~/.bashrc or ~/.zshrc
if [ -f ~/.docker_functions ]; then
source ~/.docker_functions
fi
Then place all your Docker functions in ~/.docker_functions for better organization.
Understanding the Key Components
The Table Format: The --format "table {{.Names}}\t{{.Status}}\t{{.Image}}" part creates a formatted table with the specified columns.
The Header Preservation: The (read -r header && echo "$header" && sort) part:
Creates a subshell with parentheses
Reads the first line (header) into a variable
Outputs that header first
Then sorts the remaining lines
Available Format Options: You can use any of these placeholders in your format string:
{{.ID}} – Container ID
{{.Names}} – Container name
{{.Image}} – Image name
{{.Status}} – Container status
{{.RunningFor}} – Time since container started
{{.Ports}} – Exposed ports
{{.Command}} – Command being run
{{.Size}} – Container size
More advanced docker ps command sorting bash functions
Sort containers by memory usage: Find containers consuming the most memory
This function pulls memory usage statistics from all running containers and sorts them in descending order. The output shows container names, memory usage percentages, and container IDs, helping you quickly identify memory-intensive containers. This is particularly useful for resource optimization in production environments.
List containers by uptime (oldest first): Display containers sorted by how long they’ve been running
This function lists containers by uptime, showing the oldest running containers first. The output is formatted into columns for readability. This is helpful for identifying long-running containers that might need updates or rotation as part of maintenance procedures.
This function groups and counts running containers by their base image, displaying results in descending order. This gives you a quick overview of which images are most deployed in your environment, which is useful for security audits or update planning.
Find containers with port conflicts: Identify containers that might have overlapping port mappings
This complex function analyzes port mappings across all containers to identify potential conflicts where multiple containers might be trying to use the same host port. It parses the output, extracts port information, and flags containers with matching port assignments, helping prevent unexpected behavior in networked applications.
Monitor containers with high CPU spikes: Track containers exceeding a defined CPU threshold
This monitoring function continuously checks for containers that exceed a specified CPU usage threshold (defaulting to 50% if not specified). It refreshes every 5 seconds and highlights containers with high CPU consumption, making it easy to identify performance issues in real-time during debugging or load testing scenarios.
Analyze container networking: Sort containers by network traffic volume
This sophisticated function analyzes network I/O for all containers, converts the various units (kB, MB, GB) to a common scale, sorts by the highest network traffic, and displays the top 10 bandwidth-consuming containers. This is invaluable for identifying containers that might be experiencing network bottlenecks or abnormal traffic patterns.
Health status dashboard: Create a colored overview of container health status
docker_health_dashboard() {
docker ps --format "{{.Names}}\t{{.Status}}" | \
awk '{
container_name = $1;
# Remove the first field and preserve the rest as status
$1 = "";
status = $0;
printf "%s\t", container_name;
if (status ~ /\(unhealthy\)/) {
printf "\033[31mUNHEALTHY\033[0m\n";
} else if (status ~ /\(healthy\)/) {
printf "\033[32mHEALTHY\033[0m\n";
} else if (status ~ /Up/ && status !~ /health/) {
printf "\033[33mUP (NO HEALTH CHECK)\033[0m\n";
} else if (status ~ /Restarting/) {
printf "\033[35mRESTARTING\033[0m\n";
} else {
printf "\033[31mCRITICAL\033[0m\n";
}
}' | \
column -t -s $'\t'
}
This function creates a colorful health dashboard showing the status of all containers with intuitive color coding: green for healthy, red for unhealthy, yellow for running without health checks, and purple for restarting containers. This provides a quick visual overview of your container fleet’s health, making it easy to spot issues at a glance.
This Bash function improves your workflow when managing multiple Docker containers. It’s especially useful on busy systems and helps you quickly identify important containers based on sorting logic you define.
Frequently Asked Questions (FAQ)
Can I sort by CPU or memory usage?
Not directly with docker ps, but you can use docker stats with custom scripts or tools like ctop.
Will this work on Zsh or Fish?
You may need to adjust syntax slightly depending on your shell, but the concept remains the same.
Can I use this for remote Docker hosts?
Yes, if your Docker client is set to communicate with a remote host, the function works just the same.
What if I want to filter specific containers?
You could add a grep command before the sort to filter container names or statuses based on your needs.
How can I improve the functionality further?
Consider integrating error handling and additional sorting options based on your typical usage scenarios.