Wie man den Status von Docker-Containern überprüft

DockerDockerBeginner
Jetzt üben

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

Introduction

Docker has revolutionized the way we develop, deploy, and manage applications. As a powerful containerization platform, Docker allows you to package your applications and their dependencies into isolated, portable environments. Knowing how to check the status of your Docker containers is crucial for effective management and troubleshooting.

In this hands-on lab, you will learn the essential commands to monitor your Docker containers, understand their status, and manage their lifecycle. By the end of this tutorial, you will be able to confidently check and manage the status of your Docker containers for efficient application development and deployment.

Creating and Running a Docker Container

Before we can check the status of Docker containers, we need to have some containers running. In this step, we will create and run a simple Docker container.

Understanding Docker Containers

Docker containers are lightweight, standalone, executable software packages that include everything needed to run an application: code, runtime, system tools, libraries, and settings. They provide consistent environments across different stages of development.

Benefits of using Docker containers include:

  • Consistent runtime environments
  • Isolation from other applications
  • Quick deployment and scaling
  • Efficient resource utilization

Verifying Docker Installation

Let's first verify that Docker is properly installed on the system:

docker --version

You should see output similar to:

Docker version 20.10.21, build baeda1f

Running Your First Container

Let's run a simple container using the official Nginx web server image. This will give us a container to monitor in the following steps.

Run the following command in your terminal:

docker run --name my-nginx -d -p 8080:80 nginx

This command:

  • Creates a container named my-nginx
  • Runs it in detached mode (-d), meaning it runs in the background
  • Maps port 8080 of the host to port 80 of the container (-p 8080:80)
  • Uses the official nginx image from Docker Hub

You should see a long string of characters, which is the container ID:

a72369167c214c20247f786a47b6b0b8581b60324bd2d151a7a0db8ddb024959

Now let's verify the container is running:

docker ps

You should see output similar to:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
a72369167c21   nginx     "/docker-entrypoint.…"   10 seconds ago   Up 9 seconds    0.0.0.0:8080->80/tcp   my-nginx

Congratulations! You have successfully created and started a Docker container. In the next step, we will explore how to check the status of this container in more detail.

Basic Container Status Commands

Now that we have a running container, let's learn how to check its status using Docker's most common commands.

Using docker ps Command

The docker ps command is the most fundamental way to view running containers.

docker ps

The output should look similar to:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
a72369167c21   nginx     "/docker-entrypoint.…"   2 minutes ago    Up 2 minutes    0.0.0.0:8080->80/tcp   my-nginx

This command shows:

  • CONTAINER ID: The unique identifier for the container
  • IMAGE: The Docker image used to create the container
  • COMMAND: The command executed within the container
  • CREATED: When the container was created
  • STATUS: The current status of the container
  • PORTS: Port mappings between host and container
  • NAMES: The assigned name of the container

Viewing All Containers

The basic docker ps command only shows running containers. To see all containers, including stopped ones, use:

docker ps -a

This will display all containers, regardless of their state:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
a72369167c21   nginx     "/docker-entrypoint.…"   5 minutes ago    Up 5 minutes    0.0.0.0:8080->80/tcp   my-nginx

Currently, we only have one container, but if you had stopped containers, they would appear here too.

Container Status with Formatting

You can customize the output of docker ps to show only the information you need, using the --format option:

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

This will display a simplified table with just the container names, status, and ports:

NAMES       STATUS          PORTS
my-nginx    Up 7 minutes    0.0.0.0:8080->80/tcp

Stopping a Container

Let's stop our container to see how its status changes:

docker stop my-nginx

Output:

my-nginx

Now check the status again:

docker ps

You'll notice the container is no longer listed in the running containers. To see it, use:

docker ps -a

Output:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS     NAMES
a72369167c21   nginx     "/docker-entrypoint.…"   10 minutes ago   Exited (0) 10 seconds ago             my-nginx

The container's status has changed to "Exited", indicating it's no longer running.

Starting a Container

Let's start the container again:

docker start my-nginx

Output:

my-nginx

Check the status to confirm it's running:

docker ps

Output:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
a72369167c21   nginx     "/docker-entrypoint.…"   12 minutes ago   Up 5 seconds    0.0.0.0:8080->80/tcp   my-nginx

Great! You now understand how to check the basic status of Docker containers using the docker ps command, and how to stop and start containers.

Advanced Container Monitoring

Now that you understand the basics of checking container status, let's explore more advanced monitoring commands that provide detailed information about your containers.

Detailed Container Information with docker inspect

The docker inspect command provides detailed configuration and runtime information about a container:

docker inspect my-nginx

This command returns a JSON array with comprehensive information about the container. The output is quite lengthy, but it includes:

  • Network settings
  • Volume mounts
  • Environment variables
  • Resource limits
  • Container state
  • And much more

Let's look at a specific section using the --format option:

docker inspect --format='{{.State.Status}}' my-nginx

Output:

running

You can extract other specific pieces of information:

docker inspect --format='{{.NetworkSettings.IPAddress}}' my-nginx

This will show the container's internal IP address.

Real-time Container Metrics with docker stats

The docker stats command provides a live stream of container resource usage statistics:

docker stats my-nginx

You'll see output similar to:

CONTAINER ID   NAME       CPU %     MEM USAGE / LIMIT     MEM %     NET I/O           BLOCK I/O        PIDS
a72369167c21   my-nginx   0.00%     2.312MiB / 7.764GiB   0.03%     1.05kB / 1.51kB   0B / 4.1kB       2

This shows:

  • CPU usage percentage
  • Memory usage
  • Network I/O
  • Block I/O
  • Number of processes

Press Ctrl+C to exit the live stats view.

To see stats for all containers at once:

docker stats --no-stream

This shows a snapshot of the stats without the continuous updates.

Viewing Container Logs

To troubleshoot issues, it's often useful to check the container's logs:

docker logs my-nginx

You'll see the logs from the Nginx server. If you've accessed the web server, you'll see HTTP request logs.

To follow the logs in real-time (similar to tail -f):

docker logs -f my-nginx

Press Ctrl+C to exit the log stream.

Checking Container Processes

To see the processes running inside a container:

docker top my-nginx

Output will look similar to:

UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                12345               12321               0                   14:15               ?                   00:00:00            nginx: master process nginx -g daemon off;
systemd+            12401               12345               0                   14:15               ?                   00:00:00            nginx: worker process

This shows all the processes running inside the container, their PIDs, and resource usage.

Creating a New Container for Comparison

Let's create another container to compare with our existing one:

docker run --name redis-server -d redis

Now let's compare the stats of both containers:

docker stats --no-stream my-nginx redis-server

You should see statistics for both containers, allowing you to compare their resource usage.

These advanced monitoring commands give you deeper insights into your containers' health and performance, which is essential for troubleshooting issues and optimizing resource usage.

Managing Container Lifecycle

Understanding how to manage a container's lifecycle is crucial for effective Docker usage. In this step, we'll explore various commands to control container states and understand the container lifecycle.

Container Lifecycle States

A Docker container can exist in several states:

  • Created: Container is created but not started
  • Running: Container is currently running
  • Paused: Container execution is paused
  • Stopped: Container is stopped but still exists
  • Removed: Container is deleted

Let's explore how to transition between these states.

Creating a Container Without Starting It

You can create a container without starting it using the create command:

docker create --name test-container nginx

This creates a container but doesn't start it. Check its status:

docker ps -a

You should see the new container with a "Created" status:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS                  NAMES
3f4ab92d1234   nginx     "/docker-entrypoint.…"   5 seconds ago    Created                                            test-container
a72369167c21   nginx     "/docker-entrypoint.…"   40 minutes ago   Up 30 minutes               0.0.0.0:8080->80/tcp   my-nginx
bc123def456a   redis     "docker-entrypoint.s…"   10 minutes ago   Up 10 minutes               6379/tcp               redis-server

Starting a Created Container

To start the created container:

docker start test-container

Verify it's running:

docker ps

Pausing and Unpausing Containers

Docker allows you to pause a container, which freezes all processes inside it:

docker pause test-container

Check its status:

docker ps

Output:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                  PORTS                  NAMES
3f4ab92d1234   nginx     "/docker-entrypoint.…"   2 minutes ago    Up 1 minute (Paused)                           test-container
a72369167c21   nginx     "/docker-entrypoint.…"   42 minutes ago   Up 32 minutes           0.0.0.0:8080->80/tcp   my-nginx
bc123def456a   redis     "docker-entrypoint.s…"   12 minutes ago   Up 12 minutes           6379/tcp               redis-server

To resume the container:

docker unpause test-container

Verify it's running again:

docker ps

Stopping and Restarting Containers

To stop a container gracefully (sending SIGTERM, then SIGKILL after a grace period):

docker stop test-container

To forcefully kill a container (sending SIGKILL):

docker start test-container ## Start it again first
docker kill test-container  ## Then kill it

To restart a container (stops and starts it again):

docker start test-container ## Start it again first
docker restart test-container

Removing Containers

To remove a stopped container:

docker stop test-container ## Make sure it's stopped first
docker rm test-container

Verify it's gone:

docker ps -a | grep test-container

You should get no output, indicating the container has been removed.

Removing a Running Container

You can force-remove a running container:

docker run --name temp-container -d nginx
docker rm -f temp-container

Container Restart Policies

Docker allows you to set restart policies for containers:

docker run --name always-restart --restart always -d nginx

This container will restart automatically if it exits or if Docker restarts.

Check the restart policy:

docker inspect --format='{{.HostConfig.RestartPolicy.Name}}' always-restart

Output:

always

Let's stop and remove this container:

docker rm -f always-restart

Understanding these lifecycle commands gives you complete control over your Docker containers, allowing you to efficiently manage their states based on your application needs.

Troubleshooting Container Issues

Even with proper monitoring and management, containers can sometimes encounter problems. This step will teach you how to troubleshoot common container issues using Docker's diagnostic tools.

Common Container Issues

Containers might fail due to various reasons:

  • Application crashes
  • Resource limitations
  • Configuration problems
  • Network issues
  • Permission errors

Let's explore how to identify and diagnose these issues.

Creating a Problematic Container

Let's create a container that will exit immediately due to an invalid command:

docker run --name problematic -d nginx sleep 5

This container will run the sleep 5 command and then exit after 5 seconds.

Wait a few seconds, then check its status:

docker ps -a

Output:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS                  NAMES
1a2b3c4d5e6f   nginx     "sleep 5"                10 seconds ago   Exited (0) 5 seconds ago                           problematic
a72369167c21   nginx     "/docker-entrypoint.…"   1 hour ago       Up 50 minutes               0.0.0.0:8080->80/tcp   my-nginx
bc123def456a   redis     "docker-entrypoint.s…"   30 minutes ago   Up 30 minutes               6379/tcp               redis-server

The container has exited with code 0 (success), but it's no longer running.

Checking Container Exit Codes

The exit code can tell you why a container stopped:

  • 0: Success
  • Non-zero: Error occurred

To see the exit code:

docker inspect problematic --format='{{.State.ExitCode}}'

Output:

0

This means the container exited successfully after completing its assigned task.

Examining Container Logs

Logs are crucial for troubleshooting:

docker logs problematic

In this case, you might not see any output because our sleep command doesn't produce logs.

Let's create another problematic container that will generate logs:

docker run --name crash-test -d nginx sh -c "echo 'Starting container'; sleep 2; echo 'About to crash'; exit 1"

After a few seconds, check its status and logs:

docker ps -a | grep crash-test

Output:

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS     NAMES
f1e2d3c4b5a6   nginx     "sh -c 'echo 'Starti…"   10 seconds ago   Exited (1) 7 seconds ago              crash-test

Now check the logs:

docker logs crash-test

Output:

Starting container
About to crash

These logs provide clues about what happened before the container crashed.

Checking Resource Usage

Resource constraints can cause containers to crash or perform poorly:

docker stats --no-stream my-nginx

This shows CPU, memory, and I/O usage, which can help identify resource bottlenecks.

Checking Container Configuration

Misconfiguration is a common source of issues:

docker inspect my-nginx

Look for:

  • Volume mounts
  • Environment variables
  • Network settings
  • Resource limits

Accessing a Running Container

To debug issues inside a running container:

docker exec -it my-nginx bash

This gives you a shell inside the container, where you can run commands to diagnose issues:

ls -la
ps aux
cat /etc/nginx/nginx.conf
exit ## To leave the container shell

Cleanup

Let's clean up our problematic containers:

docker rm problematic crash-test

By mastering these troubleshooting techniques, you can quickly identify and resolve issues with your Docker containers, ensuring your applications run smoothly and reliably.

Summary

In this hands-on lab, you have gained essential skills for monitoring and managing Docker containers:

  1. Creating and Running Containers - You learned how to create and run Docker containers using the docker run command.

  2. Basic Status Checking - You mastered the docker ps command to list running containers and check their basic status information.

  3. Advanced Monitoring - You explored advanced monitoring techniques using docker inspect and docker stats to get detailed container information and real-time performance metrics.

  4. Container Lifecycle Management - You learned how to manage the complete lifecycle of a container, including creating, starting, stopping, pausing, and removing containers.

  5. Troubleshooting - You developed skills to diagnose and resolve common container issues using logs, resource monitoring, and direct container access.

These skills are fundamental for effectively working with Docker containers in development, testing, and production environments. You can now confidently monitor your containers' health, manage their lifecycle, and troubleshoot issues when they arise.

To continue your Docker journey, consider exploring topics such as Docker Compose for multi-container applications, Docker networking, and container orchestration with Kubernetes.