What is the difference between a Docker image and a container?
Quick answer
An image is a read-only template made of layers that contains the application and its dependencies; a container is a running (or stopped) instance of an image with its own writable layer on top.
Detailed explanation
An image is built from a Dockerfile. Each instruction creates a layer, and layers are cached and shared between images, which makes builds and pulls faster. Images are versioned with tags and stored in registries such as Docker Hub or a private registry.
Running docker run creates a container from an image: Docker adds a thin writable layer, sets up networking and starts the process. You can run many containers from the same image, just as you create many objects from one class.
Changes made inside a container live only in its writable layer and disappear when the container is removed. Persistent data belongs in volumes, and changes to the application belong in a new image.
Example
docker build -t my-api:1.2.0 . # create an image
docker run -d --name api1 my-api:1.2.0 # start a container from it
docker run -d --name api2 my-api:1.2.0 # a second container, same image
docker ps # running containers
docker images # local imagesKey points
- Image: read-only, layered template
- Container: running instance with a writable layer
- Many containers can share one image
- Container changes are lost on removal; use volumes for data