The docker run instruction is the quickest way to spin up a new container from an image. For instance, to print a greeting and exit:
docker run debian:11-slim /bin/echo "Hello container"
The command above instructs Docker to:
- Locate the
debian:11-slimimage locally; if missing, pull it from Docker Hub. - Create a transient container from that image.
- Execute
/bin/echo "Hello container"inside the container. - Terminate the container once the command finishes.
Interactive Shell Inside a Container
To open an interactive terminal:
docker run -it --name demo-shell debian:11-slim bash
Flags explained:
-ikeeps STDIN open so you can type commands.-tallocates a pseudo-TTY, giving you a shell prompt.--name demo-shellassigns a human-readable identifier to the container.
Running a Detached Container
For long-lived services, detach the container from your terminal:
docker run -d --name looper alpine:latest \
sh -c 'while true; do echo "$(date) loop"; sleep 2; done'
The output is a unique container ID, e.g.:
3f4e8a1b9c2d7f0a9e5c8b2d4f6a1e3b5c7d9e0f2a4b6c8d0e2f4a6b8c0d2e
Inspecting Running Containers
docker ps
Typical output:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3f4e8a1b9c2d alpine:latest "sh -c 'while true; …" 30 seconds ago Up 29 seconds looper
Essential Container Operations
# Start a stopped container
docker start looper
# Gracefully stop
docker stop looper
# Force restart
docker restart looper
# Remove (must be stopped first)
docker rm looper
Connnecting to a Running Container
Two common approaches:
docker attach looper— attaches you're terminal to the main process; exiting will stop the container.docker exec -it looper sh— spawns a new shell process; exiting leaves the container running.
Image Management
# List local images
docker images
# Download an image
docker pull nginx:1.25-alpine
# Search Docker Hub
docker search redis
# Delete an image
docker rmi debian:10-slim
# Persist container changes as a new image
docker commit looper my-alpine-looper:1.0
Lifecycle Cheat Sheet
# View all containers (including exited)
docker ps -a
# Quick cleanup: stop and remove all stopped containers
docker container prune -f