# 🐳 Day 4: Mastering docker ps Command - With examlpe’s!

This guide provides a deep dive of the `docker ps` command, including how to list, filter, format, and count containers and images. Docker ps command lists containers on your system. It displays useful information such as container IDs, image names, uptime, exposed ports and many more.. It's an essential tool to working with the containers. 🐳📋

## 🎬 Video Demonstration

[![Watch on Youtube](https://camo.githubusercontent.com/ff0e51ba4fe62e7e72e3b21b5287bb8442e5f58ce9d96b8f034025d6137a0b6b/68747470733a2f2f692e7974696d672e636f6d2f76692f373376524674736e6d76492f6d617872657364656661756c742e6a7067 align="left")](https://youtu.be/73vRFtsnmvI)

## 📋 Basic Usage

### ❔ Get Help using help command

```plaintext
docker ps --help
```

```plaintext
Usage:  docker ps [OPTIONS]

List containers

Aliases:
  docker container ls, docker container list, docker container ps, docker ps

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Format output using a custom template:
                        'table':            Print output in table format with column headers (default)
                        'table TEMPLATE':   Print output in table format using the given Go template
                        'json':             Print in JSON format
                        'TEMPLATE':         Print output using the given Go template.
                        Refer to https://docs.docker.com/go/formatting/ for more information about formatting output with templates
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display container IDs
  -s, --size            Display total file sizes

```

### 1\. Show Running Containers

```plaintext
docker ps
```

### 2\. Show All Containers (Running + Stopped)

```plaintext
docker ps -a
```

### 3\. Show Disk Usage per Container

```plaintext
docker ps -s
docker ps -as

```

### 4\. Show Last N Created Containers

```plaintext
docker ps --last 4
# or
docker ps -n 4
```

### 5\. Show the Most Recently Created Container

```plaintext
docker ps -l
# or
docker ps --latest
```

### 6\. Show Only container IDs

```plaintext
docker ps -q
docker ps -aq
# or
docker ps --quiet
docker ps -a --quiet
```

---

## 🔍 Filtering Containers

### Filter by Name

```plaintext
docker ps -f "name=test-container"
or
docker ps --filter "name=test-container"
```

### Filter by Container ID

```plaintext
docker ps -a -f "id=aca09d8707d8"
or
docker ps -a --filter "id=aca09d8707d8"
```

### Filter by Status

```plaintext
docker ps --filter status=running
docker ps --filter status=exited
```

### Filter by Ancestor (Image)

```plaintext
docker ps --filter ancestor=nginx
```

### Filter by Creation Time before/after container

```plaintext
docker ps -f before=whoami
docker ps -f since=nd
```

### Sort containers by creation time (most recent first)

```plaintext
docker ps -a --format '{{.CreatedAt}}\t{{.Names}}' | sort -r
```

### Filter by Network, Volume, Port, Label, Health

```plaintext
docker ps --filter publish=8080
docker ps --filter "label=com.example.app=web"
docker ps --filter health=healthy
docker ps --filter network=bridge
docker ps --filter volume=myvol
docker ps -a --filter exited=0
```

### Multiple Filters

```plaintext
docker ps --filter status=running --filter ancestor=nginx
```

## 🔢 Counting Containers

### Count Running Containers

```plaintext
docker ps -q | wc -l
```

### Get Count via Docker Info

```plaintext
docker info --format '{{json .ContainersRunning}}'
```

### Count All Containers (Running + Stopped)

```plaintext
docker ps -a -q | wc -l
```

### Count Matching Containers by Image Name

```plaintext
docker ps | grep ibraransaridocker/coming-soon | wc -l
```

## 🛠️ Custom Formatting

### Simple Name Format

```plaintext
docker ps --format '{{.Names}}'
or
docker ps -a --format "{{.Names}}"
or
docker ps -a --format "table {{.Names}}"
```

### Detailed Format with Variables

```plaintext
FORMAT="\nID\t{{.ID}}\nIMAGE\t{{.Image}}\nCOMMAND\t{{.Command}}\nCREATED\t{{.RunningFor}}\nSTATUS\t{{.Status}}\nPORTS\t{{.Ports}}\nNAMES\t{{.Names}}\n"
docker ps -a --format="$FORMAT"
```

### Tabular Format Output

```plaintext
docker ps -a --format "table {{.Names}}\t{{.ID}}\t{{.Status}}\t{{.Ports}}\t{{.Image}}\t{{.Command}}\t{{.RunningFor}}"
```

---

## 🔍 Inspect Available Format Fields

### View Raw Output in JSON

```plaintext
docker ps --format '{{json .}}' | jq
```

### List All Available Format Keys

```plaintext
docker ps --format '{{json .}}' | jq -r 'keys_unsorted[]' | sort -u
```

### List All Format Keys from All Containers

```plaintext
# Create sample container to provide all keys
docker run -itd \
  --name test-container \
  --hostname custom-hostname \
  --env MY_ENV=example \
  --label app=demo \
  --label com.example.app=web \
  --mount type=bind,source=/tmp,target=/app/tmp,readonly \
  --mount type=volume,source=myvol,target=/app/data \
  --network bridge \
  --publish 8080:80 \
  --restart unless-stopped \
  --memory 512m \
  --cpu-shares 512 \
  --health-cmd="curl -f http://localhost || exit 1" \
  --health-interval=30s \
  --health-retries=3 \
  --health-start-period=5s \
  nginx:latest

# Run to get key
docker inspect $(docker ps -q) | jq '.[0] | keys_unsorted' | sort -u
# or
docker inspect $(docker ps -q) | jq -r '.[0] | keys_unsorted[]' | sort -u

```

---

## 🧩 All Available `--format` Fields

Here are all the fields you can use with `--format`:

| Field | Description |
| --- | --- |
| `.ID` | Container ID |
| `.Names` | Container name(s) |
| `.Image` | Image name |
| `.ImageID` | Image ID |
| `.Command` | Startup command |
| `.CreatedAt` | Creation time |
| `.RunningFor` | Time running |
| `.Ports` | Port mappings |
| `.Status` | Status string |
| `.Size` | Disk usage size (needs `-s`) |
| `.Labels` | All labels |
| `.Label` | Specific label (e.g., `{{.Label "key"}}`) |
| `.Mounts` | Mount points |
| `.Networks` | Networks attached |
| `.State` | Running, exited, paused, etc. |
| `.Health` | Healthcheck status |

---

## 📚 More Info

For full details, check the [official Docker formatting docs](https://docs.docker.com/engine/cli/formatting/) 📘

### Happy Dockering! 🐳✨
