Do docker containers retain file changes?

Julian Cerruti picture Julian Cerruti · Feb 18, 2015 · Viewed 25.4k times · Source

This is a very basic question, but I'm struggling a bit and would like to make sure I understand properly.

After a container is started from an image and some changes done to files within (i.e.: some data stored in the DB of a WebApp running on the container), what's the appropriate way to continue working with the same data between container stop and restart?

Is my understanding correct that once the container is stopped/finished (i.e.: exit after an interactive session), then that container is gone together with all file changes? So if I want to keep some file changes I have to commit the state of the container into a new image / new version of the image?

Answer

larsks picture larsks · Feb 18, 2015

Is my understanding correct that once the container is stopped/finished (i.e.: exit after an interactive session), then that container is gone together with all file changes?

No, a container persists after it exits, unless you started it using the --rm argument to docker run. Consider this:

$ docker run -it busybox sh
/ # date > example_file
/ # exit

Since we exited our shell, the container is no longer running:

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                   NAMES

But if we had the -a option, we can see it:

CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                      PORTS                   NAMES
79aee3e2774e        busybox:latest      "sh"                About a minute ago   Exited (0) 54 seconds ago                           loving_fermat       

And we can restart it and re-attach to it:

$ docker start 79aee3e2774e
$ docker attach  79aee3e2774e
<i press RETURN>
/ #

And the file we created earlier is still there:

/ # cat example_file
Wed Feb 18 01:51:38 UTC 2015
/ #

You can use the docker commit command to save the contents of the container into a new image, which you can then use to start new containers, or share with someone else, etc. Note, however, that if you find yourself regularly using docker commit you are probably doing yourself a disservice. In general, it is more manageable to consider containers to be read-only and generate new images using a Dockerfile and docker build.

Using this model, data is typically kept external to the container, either through host volume mounts or using a data-only container.