Skip to main content

Docker Container Management:

 Container Management: Starting & Stopping Containers, Logs & Inspect, and Resource Limits

📅 Published: Feb 2026
⏱️ Estimated Reading Time: 16 minutes
🏷️ Tags: Docker, Container Management, Logging, Resource Limits, Docker Commands


Introduction: Managing Running Containers

Creating a container is only the beginning. In production and development environments, you need to manage containers throughout their lifecycle. You need to start and stop them, view their output, inspect their configuration, and control the resources they consume.

This guide covers the essential container management operations that every Docker user must know.


Part 1: Starting and Stopping Containers

Container States

A Docker container can be in several states:

StateMeaning
CreatedContainer has been created but not started
RunningContainer processes are executing
PausedAll processes in the container are suspended
StoppedContainer has been stopped but still exists
ExitedContainer has completed execution
DeadContainer failed to stop properly

Creating and Starting Containers

Create without starting

bash
docker create --name myapp nginx

This creates the container but does not start it. The container remains in the created state until you start it.

Create and start (run)

bash
docker run --name myapp nginx

This creates and starts the container in one command.

Start an existing container

bash
docker start myapp
docker start -a myapp  # Attach to output

Stopping Containers

Graceful stop (SIGTERM)

bash
docker stop myapp
docker stop -t 30 myapp  # Wait 30 seconds before killing

The stop command sends SIGTERM to the main process. The process has 10 seconds (default) to clean up and exit. After the timeout, Docker sends SIGKILL.

Immediate kill (SIGKILL)

bash
docker kill myapp
docker kill -s HUP myapp  # Send specific signal

The kill command sends SIGKILL immediately. The process does not have a chance to clean up.

Stop all running containers

bash
docker stop $(docker ps -q)

Restarting Containers

Restart a container

bash
docker restart myapp
docker restart -t 30 myapp  # Wait 30 seconds before killing

Restart policy
Docker can automatically restart containers when they exit.

bash
# Always restart unless manually stopped
docker run --restart=always nginx

# Restart on failure (non-zero exit code)
docker run --restart=on-failure nginx

# Restart on failure, up to 5 times
docker run --restart=on-failure:5 nginx

# Never restart (default)
docker run --restart=no nginx

Pausing and Resuming

Pausing suspends all processes in the container. The container still exists but does not consume CPU.

bash
# Pause a container
docker pause myapp

# Resume a container
docker unpause myapp

# Check if container is paused
docker inspect --format='{{.State.Status}}' myapp

Removing Containers

Remove stopped containers

bash
docker rm myapp
docker rm myapp myapp2 myapp3

Force remove running container

bash
docker rm -f myapp

Remove and remove volumes

bash
docker rm -v myapp

Remove all stopped containers

bash
docker container prune
docker container prune -f  # Force without confirmation

Part 2: Logs and Inspect

Viewing Container Logs

Basic log viewing

bash
# View all logs
docker logs myapp

# View last 100 lines
docker logs --tail 100 myapp

# View logs since a timestamp
docker logs --since 2024-01-01T10:00:00 myapp

# View logs for the last 30 minutes
docker logs --since 30m myapp

# View logs with timestamps
docker logs --timestamps myapp

Following logs (like tail -f)

bash
# Follow logs in real-time
docker logs -f myapp

# Follow last 50 lines and continue
docker logs -f --tail 50 myapp

Log Drivers

Docker supports different logging drivers. The default is json-file, which stores logs on the local disk.

bash
# Run with specific log driver
docker run --log-driver syslog --log-opt syslog-address=tcp://192.168.1.100:514 nginx

# Run with journald (Linux)
docker run --log-driver journald nginx

# Run with awslogs (CloudWatch)
docker run --log-driver awslogs --log-opt awslogs-region=us-west-2 nginx

Log Rotation

Configure log rotation to prevent disk space issues.

bash
# Max 10MB per file, keep 3 files
docker run --log-opt max-size=10m --log-opt max-file=3 nginx

Docker Inspect

The inspect command shows detailed information about a container or image.

Basic inspect

bash
docker inspect myapp
docker inspect --format='{{.State.Status}}' myapp
docker inspect --format='{{.NetworkSettings.IPAddress}}' myapp

Common inspect queries

InformationCommand
Container statusdocker inspect --format='{{.State.Status}}' myapp
Exit codedocker inspect --format='{{.State.ExitCode}}' myapp
IP addressdocker inspect --format='{{.NetworkSettings.IPAddress}}' myapp
Port mappingsdocker inspect --format='{{.NetworkSettings.Ports}}' myapp
Mounted volumesdocker inspect --format='{{.Mounts}}' myapp
Environment variablesdocker inspect --format='{{.Config.Env}}' myapp
Created timedocker inspect --format='{{.Created}}' myapp
Restart policydocker inspect --format='{{.HostConfig.RestartPolicy}}' myapp

JSON formatting

bash
# Pretty JSON output
docker inspect myapp | jq .

# Select specific array element
docker inspect myapp | jq '.[0].NetworkSettings.IPAddress'

Part 3: Resource Limits

Why Limit Resources

Without resource limits, a single container can consume all available resources on a host. This can cause:

  • Other containers to starve for CPU

  • Host system to become unresponsive

  • Out-of-memory errors affecting other processes

  • Network bandwidth contention

Resource limits protect the host and other containers.

CPU Limits

CPU shares (relative weight)
CPU shares define the relative importance of a container. When CPU is constrained, containers with higher shares get more CPU time.

bash
# Default share is 1024
docker run --cpu-shares 512 nginx  # Half the weight of default
docker run --cpu-shares 2048 nginx  # Twice the weight of default

If two containers are running and both need CPU, a container with 2048 shares gets twice as much CPU as a container with 1024 shares.

CPU cores (absolute limit)
Limit the number of CPU cores a container can use.

bash
# Use 1.5 cores maximum
docker run --cpus 1.5 nginx

# Use 2 cores maximum
docker run --cpus 2 nginx

CPU period and quota (advanced)
Control CPU allocation more precisely.

bash
# Allow 50% of one CPU every 100ms period
docker run --cpu-period=100000 --cpu-quota=50000 nginx

# Allow 2 full CPUs
docker run --cpu-period=100000 --cpu-quota=200000 nginx

CPU set (pin to specific cores)
Assign containers to specific CPU cores.

bash
# Use CPU cores 0 and 1
docker run --cpuset-cpus 0-1 nginx

# Use CPU cores 0, 2, and 4
docker run --cpuset-cpus 0,2,4 nginx

Memory Limits

Memory limit

bash
# Limit to 512 MB
docker run --memory 512m nginx

# Limit to 2 GB
docker run --memory 2g nginx

If a container exceeds its memory limit, Docker may kill it (OOM kill).

Memory reservation (soft limit)
Memory reservation is a soft limit. Docker tries to keep memory below this but may exceed it if needed.

bash
# Reserve 256 MB, hard limit 1 GB
docker run --memory 1g --memory-reservation 256m nginx

Swap limit
Control swap usage. Swap must be enabled on the host.

bash
# Limit to 1 GB memory, 512 MB swap
docker run --memory 1g --memory-swap 1.5g nginx

# Disable swap entirely
docker run --memory 1g --memory-swap -1 nginx

# Allow unlimited swap (default)
docker run --memory 1g --memory-swap 0 nginx

Kernel memory
Limit kernel memory usage.

bash
docker run --kernel-memory 256m nginx

I/O Limits

Block I/O weight (relative)
Set I/O priority relative to other containers.

bash
# Default weight is 500
docker run --blkio-weight 300 nginx  # Lower priority
docker run --blkio-weight 800 nginx  # Higher priority

Block I/O read/write limits
Limit read and write rates per device.

bash
# Limit read to 10 MB/s
docker run --device-read-bps /dev/sda:10mb nginx

# Limit write to 20 MB/s
docker run --device-write-bps /dev/sda:20mb nginx

# Limit read IOPS
docker run --device-read-iops /dev/sda:100 nginx

Process Limits

PID limit
Limit the number of processes in a container.

bash
# Limit to 100 processes
docker run --pids-limit 100 nginx

Checking Resource Usage

Docker stats
View real-time resource usage of running containers.

bash
# View all containers
docker stats

# View specific containers
docker stats myapp myapp2

# View without streaming (one-time)
docker stats --no-stream

Docker inspect for resource limits

bash
docker inspect --format='{{.HostConfig.Memory}}' myapp
docker inspect --format='{{.HostConfig.CpuShares}}' myapp
docker inspect --format='{{.HostConfig.CpusetCpus}}' myapp

Real-World Scenarios

Scenario 1: Production Web Server

A production web server needs guaranteed resources but should not consume the entire host.

bash
docker run -d \
  --name webserver \
  --restart always \
  --cpus 1 \
  --memory 512m \
  --memory-reservation 256m \
  --pids-limit 200 \
  -p 80:80 \
  nginx

What these limits do:

  • CPU limited to 1 core

  • Memory hard limit of 512 MB, soft limit of 256 MB

  • Maximum 200 processes

  • Restarts automatically if it exits


Scenario 2: Batch Processing Job

A batch processing job should use as much resource as possible when running but should not interfere with other workloads.

bash
docker run \
  --name batch-job \
  --rm \
  --cpu-shares 2048 \
  --cpus 4 \
  --memory 4g \
  batch-image

What these limits do:

  • Higher CPU share than other containers

  • Can use up to 4 CPU cores

  • Can use up to 4 GB memory

  • Removed automatically after completion


Scenario 3: Database Container

A database needs consistent performance but must be protected from out-of-memory issues.

bash
docker run -d \
  --name postgres \
  --restart unless-stopped \
  --cpus 2 \
  --memory 4g \
  --memory-swap 6g \
  --blkio-weight 800 \
  -v postgres-data:/var/lib/postgresql/data \
  postgres:15

What these limits do:

  • 2 CPU cores dedicated

  • 4 GB memory, 6 GB total with swap

  • Higher I/O priority

  • Persistent volume for data

  • Restarts unless manually stopped


Scenario 4: Development Environment

A development container should have access to all resources but be easily removed when done.

bash
docker run -it \
  --name dev-environment \
  --rm \
  --cpus 2 \
  --memory 2g \
  -v $(pwd):/workspace \
  node:18 /bin/bash

What these limits do:

  • 2 CPU cores

  • 2 GB memory

  • Removed automatically on exit

  • Current directory mounted for development


Troubleshooting Container Management

Container Won't Stop

If a container does not respond to docker stop, try:

bash
# Give it more time
docker stop -t 60 myapp

# Force kill
docker kill myapp

# If still not working, restart Docker daemon (last resort)
sudo systemctl restart docker

Logs Growing Too Large

If container logs are consuming too much disk space:

bash
# Check log size
docker inspect --format='{{.LogPath}}' myapp
ls -lh $(docker inspect --format='{{.LogPath}}' myapp)

# Rotate logs immediately
docker run -d --log-opt max-size=10m --log-opt max-file=3 nginx

# For existing container, you need to recreate it

OOM Killed

If a container is being killed due to memory limits:

bash
# Check exit code (137 = OOM)
docker inspect --format='{{.State.ExitCode}}' myapp

# Check if OOM was the cause
docker inspect --format='{{.State.OOMKilled}}' myapp

# Increase memory limit
docker update --memory 2g myapp

# Or investigate memory usage
docker stats myapp

Container Not Starting

If a container fails to start:

bash
# Check logs
docker logs myapp

# Check container details
docker inspect myapp

# Try running with interactive shell to debug
docker run -it myapp /bin/sh

Summary

OperationCommandPurpose
Startdocker startStart stopped container
Stopdocker stopGraceful stop
Killdocker killImmediate stop
Restartdocker restartStop then start
Logsdocker logsView container output
Inspectdocker inspectView container details
Statsdocker statsView resource usage
CPU limit--cpus--cpu-sharesControl CPU usage
Memory limit--memoryControl memory usage
I/O limit--blkio-weightControl disk I/O

Effective container management ensures your applications run reliably and do not interfere with each other.


Practice Questions

  1. What is the difference between docker stop and docker kill?

  2. How do you view the last 50 lines of a container's logs and continue following new output?

  3. What command shows real-time resource usage of running containers?

  4. A container is using too much CPU and affecting other containers. How would you limit it?

  5. How do you ensure a container restarts automatically if it crashes, but does not restart if you manually stop it?


Learn More

Practice container management with hands-on exercises in our interactive labs:
https://devops.trainwithsky.com/

Comments

Popular posts from this blog

Introduction to Terraform – The Future of Infrastructure as Code

  Introduction to Terraform – The Future of Infrastructure as Code In today’s fast-paced DevOps world, managing infrastructure manually is outdated . This is where Terraform comes in—a powerful Infrastructure as Code (IaC) tool that allows you to define, provision, and manage cloud infrastructure efficiently . Whether you're working with AWS, Azure, Google Cloud, or on-premises servers , Terraform provides a declarative, automation-first approach to infrastructure deployment. Shape Your Future with AI & Infinite Knowledge...!! Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! In today’s digital-first world, agility and automation are no longer optional—they’re essential. Companies across the globe are rapidly shifting their operations to the cloud to keep up with the pace of innovatio...

📊 Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd

  Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd Monitoring and logging are essential for maintaining a healthy and well-performing Kubernetes cluster. In this guide, we’ll cover why monitoring is important, key monitoring tools like Prometheus and Grafana, and logging tools like Fluentd to help you gain visibility into your cluster’s performance and logs. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction In today’s fast-paced cloud-native environment, Kubernetes has emerged as the de-facto container orchestration platform. But deploying and managing applications in Kubernetes is just half the ba...

🔒 Kubernetes Security – RBAC, Network Policies, and Secrets Management

  Kubernetes Security – RBAC, Network Policies, and Secrets Management Security is a critical aspect of managing Kubernetes clusters. In this guide, we'll cover essential security mechanisms like Role-Based Access Control (RBAC) , Network Policies , and Secrets Management to help you secure your Kubernetes environment effectively. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction: Why Kubernetes Security Is Non-Negotiable As Kubernetes becomes the backbone of modern cloud-native infrastructure, security is no longer optional—it’s mission-critical . With multiple moving parts like containers, pods, services, nodes, and more, Kuberne...