Day 4: Basic Docker Commands - run, ps, stop, rm

Learning Objectives: By the end of this lesson, you will be able to:

  • Master the four fundamental Docker commands for container lifecycle management
  • Understand how to run containers in different modes (foreground, background, interactive)
  • List running and stopped containers with various filtering options
  • Properly stop and remove containers to manage system resources
  • Apply best practices for container naming and resource management

1. Welcome and Introduction (5 minutes)

Icebreaker Activity

Think about your smartphone: How do you open apps, see what’s running, close apps, and uninstall them? Docker containers work similarly - you need commands to start them, check their status, stop them, and remove them when no longer needed.

Lesson Overview

  • Duration: 45-60 minutes
  • Prerequisites: Docker installed and basic understanding of containers
  • Materials Needed: Terminal/command prompt, Docker running

2. Learning Objectives and Session Outline (5 minutes)

What We’ll Cover Today:

  1. docker run - Starting containers with various options
  2. docker ps - Monitoring container status and information
  3. docker stop - Gracefully shutting down containers
  4. docker rm - Cleaning up stopped containers
  5. Practical workflows combining these commands
  6. Common flags and options for each command

Success Criteria:

By the end of this session, you should be able to confidently manage the complete lifecycle of Docker containers using these four essential commands.

3. Foundation Knowledge (15-20 minutes)

The Container Lifecycle

Understanding the container lifecycle is crucial for effective Docker usage:

  1. Created - Container exists but hasn’t started
  2. Running - Container is actively executing
  3. Stopped/Exited - Container has finished execution
  4. Removed - Container is deleted from the system

Real-World Analogy: Think of containers like applications on your computer. You launch them (run), check what’s running (ps), close them (stop), and uninstall them (rm).

Why This Matters: Proper container lifecycle management prevents resource waste, ensures system performance, and maintains a clean development environment.

Key Terminology

  • Container ID: Unique identifier for each container (short and long versions)
  • Container Name: Human-readable name for easier reference
  • Image: Template used to create containers
  • Process: The main application running inside the container
  • Exit Code: Status code indicating how a container stopped (0 = success, non-zero = error)

4. Detailed Explanation and Examples (25-30 minutes)

Understanding the Four Essential Commands

These four commands form the foundation of Docker container management. Each serves a specific purpose in the container lifecycle, and mastering them is essential for any Docker user.

The Command Hierarchy

  • docker run creates and starts containers
  • docker ps shows container status
  • docker stop gracefully stops running containers
  • docker rm removes stopped containers

Common Misconceptions

  1. Misconception: Stopped containers are automatically deleted Reality: Stopped containers remain on your system until explicitly removed

  2. Misconception: docker ps only shows running containers Reality: By default it shows running containers, but flags can show all containers

  3. Misconception: You can remove running containers directly Reality: Containers must be stopped before removal (unless using force flags)

5. Live Coding Demonstration (20-25 minutes)

Example 1: Basic Container Operations

# Run a simple container that prints "Hello World" and exits
docker run hello-world

# Run Ubuntu container interactively
docker run -it ubuntu bash

# Inside the container, try some commands:
# ls
# pwd
# echo "I'm inside a container!"
# exit

Explanation:

  • docker run creates and starts a new container
  • hello-world is a minimal image for testing Docker installation
  • -it flags provide interactive terminal access
  • bash is the command to run inside the Ubuntu container

Example 2: Background Containers and Monitoring

# Run nginx web server in background (detached mode)
docker run -d --name my-nginx nginx

# List running containers
docker ps

# List all containers (running and stopped)
docker ps -a

# Get detailed information about a specific container
docker ps --filter "name=my-nginx"

Key Points:

  • -d flag runs containers in detached (background) mode
  • --name assigns a custom name for easier reference
  • docker ps without flags shows only running containers
  • -a flag shows all containers regardless of status

Example 3: Stopping and Removing Containers

# Stop the nginx container gracefully
docker stop my-nginx

# Verify it's stopped
docker ps -a

# Remove the stopped container
docker rm my-nginx

# Verify removal
docker ps -a

Example 4: Advanced Operations

# Run multiple containers
docker run -d --name web1 nginx
docker run -d --name web2 nginx
docker run -d --name web3 nginx

# List only running containers with specific format
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

# Stop multiple containers at once
docker stop web1 web2 web3

# Remove multiple containers at once
docker rm web1 web2 web3

# Force remove a running container (not recommended for production)
docker run -d --name force-demo nginx
docker rm -f force-demo

Debugging Demonstration

Show common errors and solutions:

# Error: Trying to remove a running container
docker run -d --name demo nginx
docker rm demo  # This will fail

# Solution: Stop first, then remove
docker stop demo
docker rm demo

# Error: Container name already exists
docker run --name demo nginx
docker run --name demo nginx  # This will fail

# Solution: Use different names or remove existing container
docker rm demo
docker run --name demo nginx

6. Hands-On Practice (30-40 minutes)

Exercise 1: Basic Container Lifecycle (10 minutes)

Objective: Practice the complete lifecycle of a container

Instructions:

  1. Run a Ubuntu container in interactive mode
  2. Install a package inside the container (like curl)
  3. Exit the container
  4. List all containers to see your stopped container
  5. Remove the container

Starter Commands:

# Start here
docker run -it --name my-ubuntu ubuntu bash
# Inside container: apt update && apt install -y curl
# exit
# Continue with ps and rm commands

Solution:

# Step 1: Run interactive Ubuntu container
docker run -it --name my-ubuntu ubuntu bash

# Step 2: Inside the container, install curl
apt update
apt install -y curl
exit

# Step 3: List all containers
docker ps -a

# Step 4: Remove the container
docker rm my-ubuntu

# Step 5: Verify removal
docker ps -a

Exercise 2: Managing Multiple Containers (15 minutes)

Objective: Handle multiple containers efficiently

Requirements:

  • Create 3 nginx containers with names: web-prod, web-dev, web-test
  • List only the running containers with custom formatting
  • Stop only the dev and test containers
  • Remove all stopped containers

Hints:

  • Use meaningful names for easier management
  • Practice using multiple container names in single commands
  • Use docker ps formatting to see relevant information

Solution:

# Create 3 nginx containers
docker run -d --name web-prod nginx
docker run -d --name web-dev nginx
docker run -d --name web-test nginx

# List running containers with custom format
docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}"

# Stop dev and test containers
docker stop web-dev web-test

# Remove stopped containers
docker rm web-dev web-test

# Verify final state
docker ps -a

Exercise 3: Container Inspection and Cleanup (15 minutes)

Objective: Practice advanced container management techniques

Challenge: Create a container management script that:

  • Runs 5 containers of different images (nginx, alpine, ubuntu, etc.)
  • Lists containers with specific filters
  • Implements a cleanup routine

Extension Ideas:

  • Use different run modes (interactive, detached, foreground)
  • Practice with container port mapping
  • Experiment with environment variables

Solution:

# Create diverse containers
docker run -d --name web-server nginx
docker run -d --name alpine-worker alpine sleep 3600
docker run -d --name ubuntu-base ubuntu sleep 3600
docker run --name hello-demo hello-world
docker run -d --name redis-cache redis

# List containers by status
echo "Running containers:"
docker ps --filter "status=running"

echo "Exited containers:"
docker ps --filter "status=exited"

# Cleanup routine
echo "Stopping all running containers..."
docker stop $(docker ps -q)

echo "Removing all containers..."
docker rm $(docker ps -aq)

echo "Final verification:"
docker ps -a

7. Common Pitfalls and Troubleshooting (10 minutes)

Frequent Mistakes

  1. Problem: Forgetting to remove stopped containers, leading to disk space issues Cause: Stopped containers still consume disk space Solution: Regularly clean up with docker rm or use docker system prune

  2. Problem: Using long container IDs instead of names Cause: Not using the --name flag when creating containers Solution: Always name your containers: docker run --name my-app nginx

  3. Problem: Trying to remove running containers Cause: Forgetting to stop containers before removal Solution: Stop first: docker stop container-name && docker rm container-name

Debugging Tips

  • Use docker ps -a to see all containers, not just running ones
  • Container IDs can be referenced by their first few characters (usually 3-4 is enough)
  • Use docker logs container-name to troubleshoot why containers stopped unexpectedly
  • The --filter flag helps narrow down container lists when you have many containers

8. Best Practices and Professional Tips (5 minutes)

Industry Standards

  • Naming Convention: Use descriptive names like myapp-prod-web instead of default random names
  • Resource Management: Regularly clean up stopped containers to prevent disk space issues
  • Monitoring: Use docker ps formatting to create custom dashboards and monitoring scripts
  • Graceful Shutdown: Always use docker stop before docker rm to allow proper cleanup

Next Steps in Your Learning Journey

  • Tomorrow: Explore Docker Hub and discover official images
  • Practice: Set up a daily routine to check and clean your Docker environment
  • Advanced: Learn about container restart policies and health checks

9. Summary and Review (5 minutes)

Key Takeaways

  1. Four Essential Commands: run, ps, stop, rm form the foundation of container management
  2. Container Lifecycle: Understanding the states helps with effective management
  3. Naming Matters: Use meaningful names for easier container identification and management

Quick Review Questions

  1. What’s the difference between docker ps and docker ps -a?
  2. Why should you stop a container before removing it?
  3. How do you run a container in the background?

Answers:

  1. docker ps shows only running containers; docker ps -a shows all containers
  2. To allow the container to shut down gracefully and clean up resources properly
  3. Use the -d (detached) flag: docker run -d nginx

For Instructors

Teaching Tips

  • Demonstrate each command live rather than just showing code
  • Encourage students to name their containers meaningfully from the start
  • Show the disk space impact of not cleaning up containers
  • Use real-world analogies to explain container states

Assessment Ideas

  • Quick quiz on command flags and their purposes
  • Practical exercise: “Clean up your Docker environment”
  • Peer review: Students explain container lifecycle to each other

Adaptation Notes

  • For beginners: Focus more on the basic four commands without too many flags
  • For advanced students: Introduce filtering, formatting, and automation scripts
  • Online delivery: Use screen sharing to show terminal output clearly
  • Time management: The hands-on practice can be extended if students need more time