Reputation: 2028
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?
Upvotes: 80
Views: 48650
Reputation: 311918
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.
Upvotes: 103
Reputation: 27443
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
Upvotes: 27