5. Docker File

📖 Dockerfile – The Recipe of Docker

A Dockerfile is like a recipe card 🍰.
It tells Docker how to build an image step by step.

Each line in a Dockerfile is an instruction, and Docker reads it from top to bottom to create the image.

👉 Fun fact: Dockerfile instructions are case-sensitive


🍰 Simple Analogy

Baking a cake 🧁

Dockerfile

Same idea — follow steps in order.


🛠️ Dockerfile Instructions (With Examples)

FROM – Base Image

Defines the base image for your application.

FROM ubuntu:latest
FROM ubuntu:latest

LABEL – Metadata

Adds information like version, maintainer, etc.

LABEL version="1.0"
LABEL version="1.0"

ENV – Environment Variable

Sets environment variables inside the image.

ENV owner="shan"
ENV owner="shan"

VOLUME – Persistent Storage

Defines a mount point for data.

VOLUME ["/data"]
VOLUME ["/data"]

WORKDIR – Working Directory

Sets the default directory for commands.

WORKDIR /lak
WORKDIR /lak

COPY – Copy Files

Copies files from host into the image.

COPY AStc /lak
COPY AStc /lak

ADD – Copy + Extra Features

Similar to COPY, but can unzip or download files.

ADD dumptar /lak
ADD dumptar /lak

RUN – Execute Commands (Build Time)

Runs commands while the image is being built.

RUN apt update && useradd -ms /bin/bash shan
RUN apt update && useradd -ms /bin/bash shan

USER – Change User

Runs container commands as a specific user.

USER shan
USER shan

EXPOSE – Open Port

Documents which port the container listens on.

EXPOSE 8080
EXPOSE 8080

CMD – Default Command

Defines the default command to run when container starts.
(Only one CMD is allowed.)

CMD ["ping", "8.8.8.8"]
CMD ["ping", "8.8.8.8"]

ENTRYPOINT – Executable Container

Makes the container behave like a command.

ENTRYPOINT ["ping"]
ENTRYPOINT ["ping"]

🎭 Foreground vs Background in Containers

A container must have a foreground process to keep running.

👉 If there is no foreground process, the container stops immediately.

✅ Example:


🏷️ Docker Tags

Tags are version labels for images.

docker tag <container_id> username/app:v1
docker tag <container_id> username/app:v1

👉 Think of it like:

📌 Fact:
If no tag is specified, Docker automatically uses latest.


📤 Building & Pushing Docker Images

Build Image

Creates an image from the Dockerfile.

docker build -t username/app:1.0 .
docker build -t username/app:1.0 .

Push Image to Docker Hub

Uploads the image to a registry.

docker push username/app:1.0
docker push username/app:1.0

👉 Just like: