Docker Images and Containers
The difference between images and containers and how to manage both
Overview
An image is a read-only template that contains everything needed to run an application: code, runtime, libraries, and settings. A container is a running (or stopped) instance created from an image. You can start many containers from a single image, and each one has its own isolated writable layer on top of the shared image layers.
Syntax / Usage
Images and containers are managed with separate sets of commands. Images are listed and removed with docker image (or docker images), while containers use docker ps and docker rm.
# List local images
docker images
# List all containers, including stopped ones
docker ps -a
# Create a container from an image
docker run --name app node:20
# Inspect and view logs
docker inspect app
docker logs app
# Remove a container, then its image
docker rm app
docker rmi node:20
Examples
Start a container, execute a command inside a running one, then stop it:
docker run -d --name redis redis
docker exec -it redis redis-cli ping
docker stop redis
Remove all stopped containers and dangling images to reclaim space:
docker container prune
docker image prune
Common Mistakes
- Trying to
docker rmian image while a container still uses it - Confusing
docker ps(running only) withdocker ps -a(all containers) - Expecting changes made inside a container to update the underlying image
- Naming collisions from reusing
--namewithout removing the old container - Accumulating dangling images from repeated builds and never pruning
See Also
docker-introduction docker-dockerfile docker-volumes