I was aware that I can build a new docker image using Dockerfile, and once you have the image you cann spawn the container. However I didn’t imagine a usecase where you have a running container, and you can build image out of it.
Why is building a image out of running container is important? Lets say you downloaded an image and made changes to configuration from inside the container using shell. The changes made will vanish once the container restarts.
Let me show you what am talking about..
Replicating the Problem
Lets execute the following command in docker.
docker run --name alpine -it alpine What this will do is download an alpine image and runs in interactive mode. You will be taken to a shell. Now create a file called “Test.txt” using the following command.
echo "Sample Text File" >> Test.txt When you list the files using ls command you should see Test.txt.
Now exit the shell using exit command. Your docker container is stopped. Remove the docker container with the following command.
docker rm alpine This is what happens in most of the cloud applications. When you stop the application, container is destroyed.
When you start the application again, it is like you are starting a new container with docker run command. However this time when you go into the shell and search for the file Test.txt you created, it is gone. You need to recreate the file.
Creating Image from Container
Now open the command prompt and execute the following command to run the alpine image.
docker run --name alpine -it alpine Create a Test.txt file again with random content. Now while you are in the shell, open another command prompt and execute the following docker command.
docker commit alpine my-alpine You will see a hash printed on your screen. Now list the images with the following command.
docker image ls 
Now exit the alpine shell running in the first command prompt. Also remove the alpine container.
Creating Container From My Alpine Image
Lets now create the container from my-alpine image by running the following command.
docker run --name my-alpine -it my-alpine Once you are in the console, you can now list the file. You will see Test.txt in the root folder. This file came from new image.
Whats the advantage you ask? If you host this image as a cloud application, and restart the application, your Test.txt file will stay (as it is now part of the image).
Ending Note
If you want to customize a container app and want to preserve the changes, you can do it using the docker commit command.


















