To create a docker image, following steps define the process:
Create a Dockerfile. A Dockerfile is a plain text file with a few lines of configuration inside it. This configruration is going to define how the container behaves, what different programs it is going to contain and what it does when it starts as a container.
The Dockerfile is then passed to the docker client.
Next, the docker client will pass the file to the docker server. The docker server will use the Dockerfile to build a usable image.
The below diagram illustrates the above process:
Creating a Dockerfile has the following flow:
Building a Dockerfile
As an example, we will create a Dockerfile to create an image that runs redis-server. Following is the content of the Dockerfile we will use to create an image:
# Use an existing docker image as a baseFROM alpine# Download an install dependenciesRUN apk add --update redis# Tell the image what to do when it starts as a containerCMD ["redis-server"]
Next, from the directory where the Dockerfile is created, run the following command:
dockerbuild.
The output of the command would look some thing like below:
[+] Building 9.8s (8/8) FINISHED => [internal] load build definition from Dockerfile 0.1s=> =>transferringdockerfile:613B0.1s=> [internal] load .dockerignore 0.0s=> =>transferringcontext:2B0.0s=> [internal] load metadata for docker.io/library/alpine:latest 4.8s=> [auth] library/alpine:pull token for registry-1.docker.io 0.0s=> [1/3] FROM docker.io/library/alpine@sha256:686d8c9dfa6f3ccfc8230bc3178d23f84eeaf7e457f36f271ab1acc53015037c 0.6s=> =>resolvedocker.io/library/alpine@sha256:686d8c9dfa6f3ccfc8230bc3178d23f84eeaf7e457f36f271ab1acc53015037c0.0s=> =>sha256:686d8c9dfa6f3ccfc8230bc3178d23f84eeaf7e457f36f271ab1acc53015037c1.64kB/1.64kB0.0s=> =>sha256:c3c58223e2af75154c4a7852d6924b4cc51a00c821553bbd9b3319481131b2e0528B/528B0.0s=> =>sha256:6e30ab57aeeef1ebca8ac5a6ea05b5dd39d54990be94e7be18bb969a02d10a3f1.49kB/1.49kB0.0s=> =>sha256:b3c136eddcbf2003d3180787cef00f39d46b9fd9e4623178282ad6a8d63ad3b02.69MB/2.69MB0.5s=> =>extractingsha256:b3c136eddcbf2003d3180787cef00f39d46b9fd9e4623178282ad6a8d63ad3b00.1s=> [2/3] RUN apk add --update redis 1.5s=> [3/3] RUN apk add --update gcc 2.5s=> exportingtoimage0.2s=> =>exportinglayers0.2s=> =>writingimagesha256:c5a737c182edf3e86517d93fff78126156a25373da067873642103e265933c90
Next, we use the id of the build image to create and start the container using docker run:
Till now, we created and started a container using a docker image. We can also go the other way and create a docker image using a running container.
Following is an example how to go about image generation using a running container:
dockerrun-italpinesh/# apk add --update redis
As can be observed above, we started a container using an alpine image and installed redis inside the container. Next, we get the id of this running container and use it to generate an image from it.