In this tutorial, we’ll cover essential Docker container lifecycle commands using the Docker CLI. You’ll learn how to create, start, list, interact with, monitor, and clean up containers.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
1. Creating and Starting a Container
-
Create a container from the official
httpdimage.
If the image isn’t available locally, Docker pulls it from Docker Hub. -
List containers (none are running yet):
-
Include stopped containers with
-a: -
Start the container by its CONTAINER ID:
-
Verify it’s running:
Table: docker container ls Field Descriptions
| Field | Description |
|---|---|
| CONTAINER ID | Short 12-character container ID |
| IMAGE | Name of the image |
| COMMAND | Entrypoint command |
| CREATED | Timestamp when created |
| STATUS | Current state and uptime |
| PORTS | Exposed ports |
| NAMES | Auto-generated container name |
2. Listing Options
Use different flags withdocker container ls to customize output:
| Flag | Description |
|---|---|
| -a | Show all containers (running and stopped) |
| -l | Show the latest created container |
| -q | Only display numeric IDs of running containers |
| -aq | Display numeric IDs of all containers (all states) |
3. Running Containers Interactively
Combine create and start withrun:
ubuntu:latest isn’t local, you’ll see the pull progress, then a shell prompt:
Detaching Without Stopping
To leave a container running and return to the host shell, pressCtrl+P then Ctrl+Q:
Detaching this way leaves the container running in the background.
4. Executing Commands in Running Containers
Run additional commands inside an active container usingexec:
5. Attaching to a Container
Useattach to connect to the primary process of a running container:
Exiting an attached session (
exit) will terminate the container’s main process.6. Stopping and Removing Containers
-
Stop a running container:
-
Remove a stopped container:
-
Prune all stopped containers:
docker container prune removes all stopped containers. Use with caution.7. Detached Mode and Naming
Run in detached mode (-d) and assign a custom name:
8. Inspecting Container Details
Retrieve full metadata withinspect:
9. Monitoring Containers
9.1 Resource Usage
Display real-time stats:9.2 Process List
Show host PIDs inside a container:9.3 Logs
View past logs:Conclusion
You’ve now mastered:- Creating, starting, and listing containers
- Interactive sessions with
run,exec, andattach - Naming, renaming, and inspecting container details
- Monitoring resource usage and logs
- Cleaning up with
stop,rm, andprune