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 -
COPY . /app
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.
EXPOSE 3000
vi) At last we add a “CMD” instruction to provide the command that should be executed once the container starts.
CMD ["node", "app.js"]
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.