The post discusses how to alter a standard docker image pulled from a Public repository in Docker hub as per your need. For the example of this post, we will pull a latest CentOS docker image and add a test directory “test_dir” and create a test file “test_fiel” into it.
Adding a directory and image in the docker image
1. First step is to pull a latest CentOS image from docker hub.
# docker pull centos Using default tag: latest latest: Pulling from library/centos d9aaf4d82f24: Pull complete Digest: sha256:4565fe2dd7f4770e825d4bd9c761a81b26e49cc9e3c9631c58cfc3188be9505a Status: Downloaded newer image for centos:latest
# docker images REPOSITORY TAG IMAGE ID CREATED SIZE centos latest d123f4e55e12 2 weeks ago 197MB
2. Once the CentOS Image is downloaded, we will run docker container based on this image with the name “centos_test”.
# docker run -it --name="centos_test" centos:latest /bin/bash [root@e121d03b20dc /]#
3. Now lets create a new directory in the container “test_dir” with a file in it as “test_file”. Also add some random text in the test_file.
[root@e121d03b20dc /]# mkdir test_dir [root@e121d03b20dc /]# cd test_dir [root@e121d03b20dc test_dir]# echo "This is a sample text" > test_file [root@e121d03b20dc test_dir]# cat test_file This is a sample text [root@e121d03b20dc test_dir]# ls -lrt total 4 -rw-r--r--. 1 root root 22 Nov 19 16:12 test_file
4. Next step is to build the new image with the docker commit command using the newly created docker container. The ‘docker commit’ command is run from docker host and not from the docker container itself.
# docker commit -m="This a test image" centos_test new_centos_image sha256:93603e53ff5329b314da097e3e5607b60cd1ce126f48cae542c083c715f069f7
Here,
-m=”This a test image” : is a Commit message.
centos_test : Name of the container from which you are creating the image.
new_centos_image: Name of the new image created.
5. After the above command is run, you would see the new image “centos_image” in the list of docker images available locally on the system.
# docker images REPOSITORY TAG IMAGE ID CREATED SIZE new_centos_image latest 93603e53ff53 52 seconds ago 197MB centos latest d123f4e55e12 2 weeks ago 197MB
Testing the new docker image
We will now test the newly created image by running a new container on it. We should be able to list the test directory and test file created in the new container.
1. Create a new container from the newly built image.
# docker images REPOSITORY TAG IMAGE ID CREATED SIZE new_centos_image latest 93603e53ff53 11 minutes ago 197MB centos latest d123f4e55e12 2 weeks ago 197MB
# docker run -it --name="image_testing" new_centos_image:latest /bin/bash [root@24bd49cd0e0e /]#
2. Check for the test directory and test file we have created earlier in the image.
[root@24bd49cd0e0e /]# ls -lrt test_dir total 4 -rw-r--r--. 1 root root 22 Nov 19 17:09 test_file [root@24bd49cd0e0e /]# cd test_dir [root@24bd49cd0e0e test_dir]# cat test_file This is a sample text