-2

I pulled Ubuntu image using docker pull.

I connect to the container using docker exec and then create a file and then exit.

Again, when I execute docker exec file is lost.

How to maintain the file in that container, I have tried dockerfile and tagging docker images, it works.

But, is there any other way to maintain the files in docker container for a longer time?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Penguin Tech
  • 63
  • 1
  • 1
  • 8
  • Check if you are doing the mistake described here: [I lose my data when the container exits](https://stackoverflow.com/questions/19585028/i-lose-my-data-when-the-container-exits) by using `docker run ...` instead of `docker start ...`. – tgogos Nov 25 '19 at 13:03
  • While the top-voted answer to that question is `docker commit`, I don't usually consider that a best practice. Better is to write a Dockerfile that includes the commands you need to run to install the software or create the files, check that into source control, and have a reproducible way to `docker build` an image. – David Maze Nov 25 '19 at 16:32

2 Answers2

1

One option is to commit your changes. After you've added the file, and while the container is still running, you should run:

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

Another option, maybe you'll want to use a volume, but that depends on your logic and needs.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

The best way to persist content in containers its with Docker Volumes:

╭─exadra37@exadra37-Vostro-470 ~/Developer/DevNull/stackoverflow  
╰─➤  sudo docker run --rm -it -v $PWD:/data ubuntu 

root@00af7ccf1d3b:/# echo "Persits data with Docker Volumes" > /data/docker-volumes.txt

root@00af7ccf1d3b:/# cat /data/docker-volumes.txt 
Persits data with Docker Volumes

root@00af7ccf1d3b:/# exit

╭─exadra37@exadra37-Vostro-470 ~/Developer/DevNull/stackoverflow  
╰─➤  ls -al
total 12
drwxr-xr-x 2 exadra37 exadra37 4096 Nov 25 15:34 .
drwxr-xr-x 8 exadra37 exadra37 4096 Nov 25 15:33 ..
-rw-r--r-- 1 root     root       33 Nov 25 15:34 docker-volumes.txt

╭─exadra37@exadra37-Vostro-470 ~/Developer/DevNull/stackoverflow  
╰─➤  cat docker-volumes.txt                                                                                                                                                                                  
Persits data with Docker Volumes

The docker command explained:

sudo docker run --rm -it -v $PWD:/data alpine 
  • I used the flag -v to map the current dir $PWD to the /data dir inside the container
  • inside the container:
    • I wrote some content to it
    • I read that same content
    • I exited the container
  • On the host:
    • I used ls -al to confirm that the file was persisted to my computer.
    • I confirmed could access that same file in my computer filesystem.
Exadra37
  • 11,244
  • 3
  • 43
  • 57