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:
- docker run - Starting containers with various options
- docker ps - Monitoring container status and information
- docker stop - Gracefully shutting down containers
- docker rm - Cleaning up stopped containers
- Practical workflows combining these commands
- 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:
- Created - Container exists but hasn’t started
- Running - Container is actively executing
- Stopped/Exited - Container has finished execution
- 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 runcreates and starts containersdocker psshows container statusdocker stopgracefully stops running containersdocker rmremoves stopped containers
Common Misconceptions
-
Misconception: Stopped containers are automatically deleted Reality: Stopped containers remain on your system until explicitly removed
-
Misconception:
docker psonly shows running containers Reality: By default it shows running containers, but flags can show all containers -
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 runcreates and starts a new containerhello-worldis a minimal image for testing Docker installation-itflags provide interactive terminal accessbashis 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:
-dflag runs containers in detached (background) mode--nameassigns a custom name for easier referencedocker pswithout flags shows only running containers-aflag 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:
- Run a Ubuntu container in interactive mode
- Install a package inside the container (like
curl) - Exit the container
- List all containers to see your stopped container
- 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 psformatting 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
-
Problem: Forgetting to remove stopped containers, leading to disk space issues Cause: Stopped containers still consume disk space Solution: Regularly clean up with
docker rmor usedocker system prune -
Problem: Using long container IDs instead of names Cause: Not using the
--nameflag when creating containers Solution: Always name your containers:docker run --name my-app nginx -
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 -ato 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-nameto troubleshoot why containers stopped unexpectedly - The
--filterflag 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-webinstead of default random names - Resource Management: Regularly clean up stopped containers to prevent disk space issues
- Monitoring: Use
docker psformatting to create custom dashboards and monitoring scripts - Graceful Shutdown: Always use
docker stopbeforedocker rmto 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
- Four Essential Commands:
run,ps,stop,rmform the foundation of container management - Container Lifecycle: Understanding the states helps with effective management
- Naming Matters: Use meaningful names for easier container identification and management
Quick Review Questions
- What’s the difference between
docker psanddocker ps -a? - Why should you stop a container before removing it?
- How do you run a container in the background?
Answers:
docker psshows only running containers;docker ps -ashows all containers- To allow the container to shut down gracefully and clean up resources properly
- 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