Steps for building custom images in Docker
For building images, we create Dockerfile and add instructions to it.
Detailed description of all instructions to create a Dockerfile are given as follows -
i) You typically start with a “FROM” instruction. This allows you to build on top of a base image.
For example,
FROM node
ii) To run all the subsequent commands where we copy our application, we need to specify working directory. For this, we use the “WORKDIR” instruction.
WORKDIR /app
iii) Install dependencies. We add instructions for installing dependencies before copying the code as docker caches the results of each and every instruction while building image layers. For every code change we do not want it to fetch and install dependencies all over again. A sample instruction for installing dependencies in case of node is given below -
COPY package.json /app
RUN npm install
“RUN” instruction executes a particular command which is provided at the time of building the image.
iv) Next, we specify which files in our application directory should go into the image -
Here, “.” represents the path where the files to be copied into the image lie and “/app” represents the path inside the image i.e. internal filesystem inside docker container.
v) We add “EXPOSE” instruction so as to specify at which port the application is listening on.
vi) At last we add a “CMD” instruction to provide the command that should be executed once the container starts.
The difference between “RUN” and “CMD” instructions is that the “RUN” instruction executes at the time image is getting created whereas “CMD” instruction executes when a container based on this image starts.
2. Once we have this Dockerfile ready, we can build an image based on this Dockerfile by executing the following command -
Here, “dockerfile_path” specifies the path in which the Dockerfile is present.
*** NOTE: EXPOSE instruction does NOT do anything. It is added only as a best practice so as to document which port will be exposed by your container. To tell docker so as to which port an internal docker container port should be made accessible to the outside network, we specify “-p” flag while running the container. For e.g. -