Dockerfile in a nutshell

Khemnath chauhan
2 min readJun 18, 2023

--

BuildDocker-Image

A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image.

dockerfile-format

The instruction is not case-sensitive. However, convention is for them to be UPPERCASE to distinguish them from arguments more easily.

Docker runs instructions in a Dockerfile in order. A Dockerfile must begin with a FROM instruction. This may be after parser directives, comments, and globally scoped ARGs. The FROM instruction specifies the Parent Image from which you are building. FROM may only be preceded by one or more ARG instructions, which declare arguments that are used in FROM lines in the Dockerfile.

COMMON DOCKERFILE COMMANDS:

FROM: Sets the base image for a build (like alpine )
RUN: Runs command in a new layer [ like Installation ]
COPY: Copies New Files and folders from local machine to new Image layer.
WORKDIR: The working directory for the container.
CMD: The main purpose of a CMD is to provide defaults for an executing container.
ENTRYPOINT: This is same as CMD, however it can't be overridden.
USER: To define a user inside the container, the default is the ROOT user.
EXPOSE: Informs docker what port the container app is running on.
ADD: This is same as COPY, but it can add from a remote URL & do extraction ( like adding application/web files)

RUN

RUN apt-get update && apt-get install python3 && apt-get clean

It’s used to run commands in the container, generally used to install packages.
Each RUN creates a new layer in our container, so we need to avoid creating too many RUN, to create fewer layers and don’t let all too messy, after all, we only have read-write access in the last layer, so depending on what we want to do, we can’t (e.g. apt-get clean in another RUN).

SAMPLE DOCKER FILE:

# syntax=docker/dockerfile:1
FROM ubuntu:18.04
COPY . /app
RUN make /app
CMD python /app/app.py

Each instruction creates one layer:

  • FROM creates a layer from the ubuntu:18.04 Docker image.
  • COPY adds files from your Docker client’s current directory.
  • RUN builds your application with make.
  • CMD specifies what command to run within the container.

EXPOSE THE CONTAINER:

docker run -p <HOST_PORT>:<CONTAINER:PORT> IMAGE_NAME

BUILD CONTAINER:

docker build -t Ex_Image:1.0 .

To build the image, we use the docker build command. We pass the -t parameter to name this image, a colon, and the version. And we use the ".", To say that our Dockerfile is at the same directory level.

--

--