Table of Contents

Docker - Docker Images vs. Container

Docker has images and containers. The two are closely related, but distinct.


Docker Images

Images are basically a template used to create containers.

Local images can be listed by running:

docker images

returns:

REPOSITORY                TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                    13.10               5e019ab7bf6d        2 months ago        180 MB
ubuntu                    14.04               99ec81b80c55        2 months ago        266 MB
ubuntu                    latest              99ec81b80c55        2 months ago        266 MB
ubuntu                    trusty              99ec81b80c55        2 months ago        266 MB
<none>                    <none>              4ab0d9120985        3 months ago        486.5 MB

Some things to note:

More info on images is available from the Docker docs.


Docker Containers

To use a programming metaphor, if an image is a class, then a container is an instance of a class — a runtime object.

Containers are hopefully why you're using Docker; they're lightweight and portable encapsulations of an environment in which to run applications.

View local running containers by running:

docker ps

returns:

CONTAINER ID        IMAGE                               COMMAND                CREATED             STATUS              PORTS                    NAMES
f2ff1af05450        samalba/docker-registry:latest      /bin/sh -c 'exec doc   4 months ago        Up 12 weeks         0.0.0.0:5000->5000/tcp   docker-registry

Here I'm running a dockerized version of the docker registry, so that I have a private place to store my images. Again, some things to note:

  1. Like IMAGE ID, CONTAINER ID is the true identifier for the container. It has the same form, but it identifies a different kind of object.
  2. docker ps only outputs running containers. You can view stopped containers with docker ps -a.
  3. NAMES can be used to identify a started container via the --name flag.

How to avoid image and container build-up

There's a constant build-up of untagged images and stopped containers which could lead to a maxed out hard drive.

We can remove all untagged images by combining docker rmi with the recent dangling=true query:

docker images -q --filter "dangling=true" | xargs docker rmi

Docker won't be able to remove images that are behind existing containers, so you may have to remove stopped containers with docker rm first:

docker rm `docker ps --no-trunc -aq`

These are known pain points with Docker, and may be addressed in future releases.

However, with a clear understanding of images and containers, these situations can be avoided with a couple of practices:

  1. Always remove a useless, stopped container with docker rm [CONTAINER_ID].
  2. Always remove the image behind a useless, stopped container with docker rmi [IMAGE_ID].