Wie man Docker-Container nach Namen filtert

DockerDockerBeginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Introduction

Docker has become an essential tool for developers and IT professionals, providing a powerful platform for containerizing applications. In this tutorial, we will explore how to filter Docker containers by name, a crucial skill for effectively managing your Docker environment. By the end of this guide, you will be able to efficiently locate and manage specific containers based on their names, empowering you to optimize your Docker workflows.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("Docker")) -.-> docker/ContainerOperationsGroup(["Container Operations"]) docker/ContainerOperationsGroup -.-> docker/ps("List Running Containers") docker/ContainerOperationsGroup -.-> docker/restart("Restart Container") docker/ContainerOperationsGroup -.-> docker/rm("Remove Container") subgraph Lab Skills docker/ps -.-> lab-417741{{"Wie man Docker-Container nach Namen filtert"}} docker/restart -.-> lab-417741{{"Wie man Docker-Container nach Namen filtert"}} docker/rm -.-> lab-417741{{"Wie man Docker-Container nach Namen filtert"}} end

Viewing Docker Containers with docker ps

Before we can filter Docker containers, we first need to understand how to view the containers that are running on our system. The most fundamental command for this purpose is docker ps.

Understanding the docker ps Command

The docker ps command lists all the running Docker containers on your system. When you run this command, you'll see information about each container, including:

  • Container ID: A unique identifier for the container
  • Image: The Docker image used to create the container
  • Command: The command that's running inside the container
  • Created: When the container was created
  • Status: The current status of the container
  • Ports: Any port mappings
  • Names: The name of the container

Let's run the docker ps command to see all the running containers:

docker ps

You should see output similar to this:

CONTAINER ID   IMAGE     COMMAND                  CREATED              STATUS              PORTS     NAMES
54a76e95d987   alpine    "sleep 1000"             About a minute ago   Up About a minute             db-server
26f8c661f7a5   alpine    "sleep 1000"             About a minute ago   Up About a minute             utility-alpine
a3bb567cc561   redis     "docker-entrypoint.s…"   About a minute ago   Up About a minute   6379/tcp  cache-server
f1d07c98e753   nginx     "/docker-entrypoint.…"   About a minute ago   Up About a minute   80/tcp    web-backend
d6fe891c1f04   nginx     "/docker-entrypoint.…"   About a minute ago   Up About a minute   80/tcp    web-frontend

Viewing All Containers

By default, docker ps only shows running containers. To see all containers, including those that have stopped, use the -a flag:

docker ps -a

This command will display all containers, regardless of their status. This is useful when you want to see containers that have exited or are paused.

Viewing Container IDs Only

If you only need the container IDs, you can use the -q flag:

docker ps -q

This outputs only the container IDs, which can be useful when you need to pass them to other commands.

Try these commands in your terminal to get familiar with the basic container listing functionality before we move on to filtering in the next step.

Basic Container Filtering by Name

Now that we understand how to list Docker containers, let's learn how to filter them by name. When you have multiple containers running, finding a specific one can be challenging. Docker provides filtering capabilities that make this task much easier.

Using the --filter Option

The docker ps command supports filtering through the --filter or -f option. The basic syntax for filtering by name is:

docker ps --filter name=<container-name>

Let's try filtering for containers that have "web" in their name:

docker ps --filter name=web

You should see output similar to this:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
f1d07c98e753   nginx     "/docker-entrypoint.…"   10 minutes ago   Up 10 minutes   80/tcp    web-backend
d6fe891c1f04   nginx     "/docker-entrypoint.…"   10 minutes ago   Up 10 minutes   80/tcp    web-frontend

Notice that both web-frontend and web-backend containers are displayed since they both contain the word "web" in their names.

Filtering for Exact Names

To filter for a container with an exact name, you can use the full name:

docker ps --filter name=web-frontend

This command will show only the container named exactly "web-frontend":

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
d6fe891c1f04   nginx     "/docker-entrypoint.…"   12 minutes ago   Up 12 minutes   80/tcp    web-frontend

Using Multiple Filters

You can apply multiple filters by adding multiple --filter options. For example, to find all containers with "web" in their name AND built from the "nginx" image:

docker ps --filter name=web --filter ancestor=nginx

The result should be the same as our first filter since both "web" containers use the nginx image:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
f1d07c98e753   nginx     "/docker-entrypoint.…"   15 minutes ago   Up 15 minutes   80/tcp    web-backend
d6fe891c1f04   nginx     "/docker-entrypoint.…"   15 minutes ago   Up 15 minutes   80/tcp    web-frontend

Filtering Containers by Start of Name

If you want to filter containers whose names start with a specific string, you can use a pattern like this:

docker ps --filter name=^db

This command will show containers whose names start with "db":

CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
54a76e95d987   alpine    "sleep 1000"  16 minutes ago   Up 16 minutes             db-server

Try these filtering commands in your terminal to practice finding specific containers by their names.

Advanced Filtering and Formatting Output

Now that we've mastered basic name filtering, let's explore some more advanced techniques for filtering and formatting the output of the docker ps command. These skills will help you manage your Docker environment more efficiently.

Combining Multiple Filtering Criteria

Docker allows you to combine multiple filtering criteria to narrow down your results. For example, to find all containers with "web" in their name that are currently running:

docker ps --filter name=web --filter status=running

This will display all running containers that have "web" in their name:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
f1d07c98e753   nginx     "/docker-entrypoint.…"   25 minutes ago   Up 25 minutes   80/tcp    web-backend
d6fe891c1f04   nginx     "/docker-entrypoint.…"   25 minutes ago   Up 25 minutes   80/tcp    web-frontend

Using the --format Option for Custom Output

The docker ps command supports custom output formatting using the --format option with Go templates. This allows you to display only the information you need in the format you want.

For example, to display only the container names and their status:

docker ps --format "table {{.Names}}\t{{.Status}}"

You'll see a simplified output like this:

NAMES               STATUS
db-server           Up 26 minutes
utility-alpine      Up 26 minutes
cache-server        Up 26 minutes
web-backend         Up 26 minutes
web-frontend        Up 26 minutes

Combining Filtering and Formatting

You can combine filtering and formatting to get exactly the information you need:

docker ps --filter name=web --format "table {{.Names}}\t{{.Image}}\t{{.Status}}"

This will display a table with names, images, and status for containers with "web" in their name:

NAMES               IMAGE               STATUS
web-backend         nginx               Up 27 minutes
web-frontend        nginx               Up 27 minutes

Using Regex-Like Filtering

Docker's filtering system supports some regex-like patterns. For instance, to find containers whose names contain either "web" OR "cache":

docker ps --filter name=web --filter name=cache

This will display both web containers and cache containers:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS      NAMES
a3bb567cc561   redis     "docker-entrypoint.s…"   30 minutes ago   Up 30 minutes   6379/tcp   cache-server
f1d07c98e753   nginx     "/docker-entrypoint.…"   30 minutes ago   Up 30 minutes   80/tcp     web-backend
d6fe891c1f04   nginx     "/docker-entrypoint.…"   30 minutes ago   Up 30 minutes   80/tcp     web-frontend

Practical Example: Container Management Script

Let's create a simple script that demonstrates how filtering can be used in a practical scenario. Create a new file called container-stats.sh with the following content:

nano container-stats.sh

Add the following script:

#!/bin/bash
## This script displays container names, images and status for a filtered set of containers

echo "Web containers:"
docker ps --filter name=web --format "{{.Names}} - {{.Image}} - {{.Status}}"

echo -e "\nCache and database containers:"
docker ps --filter name=cache --filter name=db --format "{{.Names}} - {{.Image}} - {{.Status}}"

Save the file (Ctrl+O, Enter, then Ctrl+X) and make it executable:

chmod +x container-stats.sh

Now run the script to see filtered and formatted container information:

./container-stats.sh

You should see output similar to:

Web containers:
web-backend - nginx - Up 35 minutes
web-frontend - nginx - Up 35 minutes

Cache and database containers:
cache-server - redis - Up 35 minutes
db-server - alpine - Up 35 minutes

This script demonstrates how container filtering can be used to organize and present information about your Docker environment in a more readable and useful way.

Practical Applications of Container Filtering

In this step, we will explore practical applications of container filtering to perform common Docker management tasks. These examples demonstrate how filtering can be used in real-world scenarios to make container management more efficient.

Finding and Restarting Specific Containers

Let's say you need to restart all web-related containers. You can use name filtering to identify them and then restart them:

## First, identify the web containers
docker ps --filter name=web

## Now, restart them one by one
docker restart web-frontend
docker restart web-backend

After running these commands, you should see confirmation that each container was restarted:

web-frontend
web-backend

Finding and Removing All Containers with a Specific Name Pattern

If you need to remove all containers with a certain name pattern, you can combine filtering with container removal:

## WARNING: This is for demonstration only. In a real environment,
## make sure you know what you're removing!

## List containers with "utility" in their names
docker ps -a --filter name=utility

You should see your utility container:

CONTAINER ID   IMAGE     COMMAND         CREATED          STATUS          PORTS     NAMES
26f8c661f7a5   alpine    "sleep 1000"    45 minutes ago   Up 45 minutes             utility-alpine

To remove it, you would typically use:

## We won't actually run this command to preserve our lab environment
## docker rm -f $(docker ps -aq --filter name=utility)

Instead, let's see how this command works:

## Just get the IDs that would be affected
docker ps -aq --filter name=utility

This will output the container ID:

26f8c661f7a5

Using Filtering to Monitor Specific Container Groups

Container filtering is useful for targeted monitoring. Let's create a simple monitoring script that checks the status of our web containers:

nano web-monitor.sh

Add the following script:

#!/bin/bash
## This script checks the status of web containers and reports if any are not running

echo "=== Web Container Status Check ==="
docker ps -a --filter name=web --format "{{.Names}}: {{.Status}}"

## Count stopped web containers
STOPPED=$(docker ps -a --filter name=web --filter status=exited --format "{{.Names}}" | wc -l)

if [ $STOPPED -gt 0 ]; then
  echo -e "\nWARNING: $STOPPED web containers are not running!"
else
  echo -e "\nAll web containers are running normally."
fi

Save the file (Ctrl+O, Enter, then Ctrl+X) and make it executable:

chmod +x web-monitor.sh

Now, run the script to see the status of your web containers:

./web-monitor.sh

You should see output similar to:

=== Web Container Status Check ===
web-backend: Up 50 minutes
web-frontend: Up 50 minutes

All web containers are running normally.

Filtering in CI/CD Pipelines

In CI/CD pipelines, filtering containers can be essential for automated testing and deployment. Let's create a script that simulates a deployment process that targets only containers with a specific name pattern:

nano deploy-update.sh

Add the following script:

#!/bin/bash
## This script simulates updating all containers of a specific type

TARGET_CONTAINERS=$1

if [ -z "$TARGET_CONTAINERS" ]; then
  echo "Usage: $0 <container-name-pattern>"
  exit 1
fi

echo "Preparing to update containers matching pattern: $TARGET_CONTAINERS"
echo "Containers affected:"
docker ps --filter name=$TARGET_CONTAINERS --format "{{.Names}}"

echo -e "\nIn a real deployment, this would:"
echo "1. Pull the latest images"
echo "2. Stop each container"
echo "3. Start new containers with the updated images"
echo "4. Verify the containers are running correctly"

echo -e "\nSimulation completed successfully!"

Save the file (Ctrl+O, Enter, then Ctrl+X) and make it executable:

chmod +x deploy-update.sh

Now, let's simulate updating our web containers:

./deploy-update.sh web

You should see output similar to:

Preparing to update containers matching pattern: web
Containers affected:
web-backend
web-frontend

In a real deployment, this would:
1. Pull the latest images
2. Stop each container
3. Start new containers with the updated images
4. Verify the containers are running correctly

Simulation completed successfully!

These practical examples demonstrate how container filtering can be integrated into your Docker workflow to make container management more efficient and automated.

Summary

In this lab, you have learned how to effectively filter Docker containers by name, an essential skill for managing Docker environments of any size. Let's review what we've covered:

  1. Basic Container Listing: You learned how to use the docker ps command to view running containers and its various options like -a for showing all containers.

  2. Basic Name Filtering: You discovered how to use the --filter name= option to find containers by name, both exact matches and partial matches.

  3. Advanced Filtering and Formatting: You explored how to combine multiple filters and customize output using the --format option to display only the information you need.

  4. Practical Applications: You created scripts that demonstrate real-world uses of container filtering for monitoring, management, and deployment tasks.

These skills will help you manage Docker environments more efficiently, especially as the number of containers grows. Container filtering is particularly valuable in development, testing, and production environments where you need to quickly identify and manage specific containers.

As you continue your Docker journey, consider exploring other filtering options beyond name filtering, such as filtering by volume, network, or label. These additional filtering techniques can further enhance your container management capabilities.