Import an image from a local directory with new configurations
In the previous steps, you imported images from tarball files. In this step, you will learn how to import an image from a local directory and apply new configurations during the import process. This is useful when you have a filesystem snapshot in a directory and want to turn it into a Docker image with specific settings like the command to run.
First, let's create a simple directory structure and a file that will be included in our image.
mkdir ~/project/myimage
echo "Hello, Docker!" > ~/project/myimage/hello.txt
This creates a directory named myimage inside your ~/project directory and a file named hello.txt within it containing the text "Hello, Docker!".
Now, we will use the docker image import command to import the content of the ~/project/myimage directory. We will also use the -c flag to specify configuration changes for the image. In this case, we will set the CMD instruction, which defines the default command to execute when a container is started from this image.
docker image import -c 'CMD ["/bin/cat", "/hello.txt"]' ~/project/myimage myimage:latest
In this command:
-c 'CMD ["/bin/cat", "/hello.txt"]' sets the default command for the image to /bin/cat /hello.txt. The -c flag allows you to apply Dockerfile instructions like CMD, ENTRYPOINT, ENV, EXPOSE, LABEL, ONBUILD, STOPSIGNAL, USER, and WORKDIR.
~/project/myimage is the path to the local directory containing the filesystem content.
myimage:latest is the desired repository and tag for the imported image.
After executing this command, Docker will create a new image based on the content of the ~/project/myimage directory and apply the specified CMD configuration.
To verify the import and the configuration, you can list the images:
docker images
You should see an image with the repository myimage and tag latest.
Now, let's run a container from this image to see if the CMD instruction is applied correctly.
docker run myimage:latest
This command starts a container from the myimage:latest image. Because we set the CMD to /bin/cat /hello.txt, the container should execute this command and print the content of the hello.txt file, which is "Hello, Docker!".
You should see "Hello, Docker!" printed to your terminal. This confirms that the directory content was imported and the CMD configuration was applied successfully.