Do docker containers retain file changes?
Solution 1:
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 exit
ed 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.
Solution 2:
You can see finished containers with docker ps -a
You can save a finished container, with the filesystem changes, into an image using docker commit container_name new_image_name
You can also extract data files from the finished container with: docker cp containerID:/path/to/find/files /path/to/put/copy
Note that you can also "plan ahead" and avoid trapping data you'll need permanently within a temporary container by having the container mount a directory from the host, e.g.
docker run -v /dir/on/host:/dir/on/container -it ubuntu:14.04