Docker saving data

2019-09-19 19:21发布

问题:

I run a container and, say, install vim. I exit out of the container. I would then like to re-run the container and have still have vim installed.

Is there a way to do this, because every time I restart a container vim is never there.

回答1:

Is there a way to do this, because every time I restart a container vim is never there

They are still there. when you run

docker ps -a

You should see all of them, some of them are not in running status, but in exited status.

There are two ways to re-use the same container. For example,

List all containers with docker ps -a

$ docker ps -a |grep 9c8e962f21e7
9c8e962f21e7        centos:6    "bash"     6 days ago    Exited (137) 2 seconds ago   boring_stallman

run with docker exec

docker start 9c8e962f21e7
docker exec -ti 9c8e962f21e7 bash

You should be fine to login and run vim if you installed it before.

run with docker attach, if the container start with bash

docker attach 9c8e962f21e7


回答2:

In Docker there are images and containers . When ever you docker run something, the something is an original copy and that is the image and is unmodified no matter what happens in the container. The copy running in the container acquires a new layer in the container's filesystem that isolates any changes to that one container.

You can use docker commit <containerid> <imagename> to save changes from the temporary container to a new permanent image.

However, for reproduction and documentation purposes it is better to do builds from a Dockerfile.

Here are the docs for docker commit.

docker commit --help

Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

  -a, --author=""     Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  --help=false        Print usage
  -m, --message=""    Commit message
  -p, --pause=true    Pause container during commit


回答3:

You should build this container from a Dockerfile. So something like

FROM ubuntu:latest
RUN apt-get install vim
CMD some command

That way the containers you run from this image have vim.

EDIT 1

Additionally, you can commit your container to an image, that way the current state of that container is saved to an image that you can spawn additional containers with the same state.