Commit a container to a new image
In this step, you will learn how to commit changes made inside a running container to a new Docker image. This is useful when you want to save the state of a container after making modifications, such as installing software or configuring files.
First, let's run a simple Ubuntu container. We will use the ubuntu image. Since we will make changes inside the container, we need to run it interactively with a pseudo-TTY.
docker run -it ubuntu
You should now be inside the Ubuntu container's shell. Let's make a simple change, like installing the curl package.
apt-get update
apt-get install -y curl
After the installation is complete, exit the container's shell by typing exit.
exit
Now that you have exited the container, the changes you made (installing curl) are still present in that specific container instance. To save these changes as a new image, you need to commit the container.
First, find the container ID of the container you just exited. You can use the docker ps -a command to list all containers, including those that have exited.
docker ps -a
Look for the container that was created from the ubuntu image and note its CONTAINER ID.
Now, use the docker commit command to create a new image from this container. The basic syntax is docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]. We will commit the container and give the new image a name and tag. Replace <CONTAINER_ID> with the actual ID you found.
docker commit < CONTAINER_ID > my-ubuntu-with-curl:v1
This command creates a new image named my-ubuntu-with-curl with the tag v1. You can verify that the new image has been created by listing your local images.
docker images
You should see my-ubuntu-with-curl in the list of images. This new image now includes the curl package that you installed in the container.