Mega Menu

Wednesday, January 08, 2020

Docker - Docker File - Key Steps Involved


Dockerfile is a file with a set of defined scripts to allow docker to create an image. Below is a simple sample file to create a redis image.

FileName - Dockerfile (No file extensions and case-sensitive file name)



 

How to use this file to create image

From the location of this file, execute the below command

docker build .

This builds the image and returns the containerId.

It is a recommendation to build docker images with tagging to uniquely identify the image and is recommended to prefix your dockerId for the tag.

docker build -t {dockerId}/{name}:{version} .
eg: docker build testid/redis:v1

       when you want to use this image, you can just refer to it as {dockerId}/{name}, which will pick the latest version of image and to refer to a specific version, append the version id {dockerId}/{name}:{version}
eg: docker run {dockerId}/{name}:{version}

What happens during the docker build process?

The log file after the build creation explains what happens as a part of the docker build. Quick outline of steps based on the sample Dockerfile (from my understanding).

Step #1 - Downloads the alpine image (small image without any installed applications. based on what is needed, find out the right base image from docker repository)
Step #2 - Creates a temporary container with alpine image
        Runs the command to download and install redis
        Creates and saves the image
        Deletes the temporary container
Step #3 - Creates a new temporary container from the image created at the end of step #2
                Adds the command redis-server as the start-up command
                Saves the image
                Deletes the temporary container
                Creates the container from the saved image and prints the Id.

If you try to re-run the docker build with the same Dockerfile on the same machine again, docker does not create all these temporary container as mentioned above, rather uses the cached images which were created in the initial build. Screenshot 2 below shows this.

If there is a change to existing Dockerfile, the docker tries to use cache for all possible images and increment the changes per the sequence in the Dockerfile.

To effectively re-use the cache and reduce the time to build an image, it is recommended to add changes to Dockerfile at the end (where possible).

 

 Screenshot of Docker build using the sample above (first time build) -



 Screenshot 2 of Docker build using the sample above (2nd consecutive build) -




Dockerfile is the default file without any extension referenced by docker build command. In order to use a custom version of this file, -f parameter to be appended to docker build command with file name.
Eg: docker build -f Dockerfile.test .


Very good tutorial on docker on Udemy here.

Detailed Dockerfile syntax and steps here

No comments:

Post a Comment