Docker & Containers

The Recipe of Docker: Dockerfiles

Lesson 5 of 9 · 9 min · Intermediate

A Dockerfile is like a recipe card . It tells Docker how to build an image step by step. Each line is an instruction, and Docker reads it from top to bottom to bake your final container image.

Baking the Cake

Think of building an image just like baking a cake. You can't bake it before you add the flour. Docker follows the exact same logical, sequential progression.

The Cake Recipe

Take flour → Add sugar → Mix → Bake in oven.

The Dockerfile

FROM ubuntu → RUN apt-get update → COPY code → CMD run app

Dockerfile Instruction Dictionary

Dockerfile
FROM ubuntu:latest
LABEL version="1.0"
ENV owner="shan"
VOLUME ["/data"]
WORKDIR /lak

COPY AStc /lak
ADD dumptar /lak
RUN apt update && useradd -ms /bin/bash shan
USER shan
EXPOSE 8080
CMD ["ping", "8.8.8.8"]

What they do

  • FROM Defines the base image. Every valid Dockerfile must start with this.
  • LABEL / ENV LABEL adds metadata (like version). ENV sets persistent environment variables inside the image.
  • WORKDIR Sets the default directory for all subsequent commands (like cd).
  • COPY / ADD Both copy files from host to image. ADD has extra features like unzipping or downloading from URLs.
  • RUN Executes commands during the build time (e.g., installing packages).
  • CMD / ENTRYPOINT Defines the default command to run when the container starts. (Only one CMD is allowed).

Foreground vs Background

A container must have a foreground process to keep running. If there is no foreground process holding the terminal open, the container completes its task and stops immediately.

Foreground Process

The main task. For example, running an Apache or Nginx server directly in the terminal. As long as the server runs, the container lives.

Background Process

Tasks running silently (like a cron job or background logging). If your CMD only starts background tasks, the container will instantly exit.

Building & Pushing Images

Tags are version labels for images (e.g., app:v1). Think of it like saving a file as Essay_v1.docx. If no tag is specified, Docker automatically applies the latest tag.

terminal

# 1. Build the Image
# (The period '.' means use the Dockerfile in current directory)
$ docker build -t username/app:1.0 .
Successfully built 8a9b2c3d4e5f
Successfully tagged username/app:1.0

# 2. Tag an existing image (optional)
$ docker tag 8a9b2c3d4e5f username/app:v1

# 3. Push to Docker Hub
$ docker push username/app:1.0
The push refers to repository [docker.io/username/app]
1.0: digest: sha256:7b8c... size: 1532
$