In Docker, what's the difference between a container and an image?

Golo Roden picture Golo Roden · Feb 1, 2014 · Viewed 84.2k times · Source

What's the difference between a container and an image in Docker? In the Get started with Docker tutorial these terms are both used, but I do not understand the difference.

Can anybody please shed some light?

Answer

cbare picture cbare · May 15, 2014

Images are frozen immutable snapshots of live containers. Containers are running (or stopped) instances of some image.

Start with the base image called 'ubuntu'. Let's run bash interactively within the ubuntu image and create a file. We'll use the -i and -t flags to give us an interactive bash shell.

$ docker run -i -t ubuntu  /bin/bash
root@48cff2e9be75:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@48cff2e9be75:/# cat > foo
This is a really important file!!!!
root@48cff2e9be75:/# exit

Don't expect that file to stick around when you exit and restart the image. You're restarting from exactly the same defined state as you started in before, not where you left off.

$ docker run -i -t ubuntu  /bin/bash
root@abf181be4379:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@abf181be4379:/# exit

But, the container, now no longer running, has state and can be saved (committed) to an image.

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                CREATED              STATUS                          PORTS                      NAMES
abf181be4379        ubuntu:14.04        /bin/bash              17 seconds ago       Exited (0) 12 seconds ago                                  elegant_ardinghelli    
48cff2e9be75        ubuntu:14.04        /bin/bash              About a minute ago   Exited (0) 50 seconds ago                                  determined_pare        
...

Let's create an image from container ID 48cff2e9be75 where we created our file:

$ docker commit 48cff2e9be75 ubuntu-foo
d0e4ae9a911d0243e95556e229c8e0873b623eeed4c7816268db090dfdd149c2

Now, we have a new image with our really important file:

$ docker run ubuntu-foo /bin/cat foo
This is a really important file!!!!

Try the command docker images. You should see your new image ubuntu-foo listed along with the ubuntu standard image we started with.