Docker

Docker

Docker is Open-Source containerization platform that enables developers and organizations to build, deploy, and manage application in isolated environments, ensuring consistency, and efficiency across various computing environments.

FeatureVirtual MachinesDocker Containers
Boot TimeMinutesSeconds
Resource UsageHeavy (OS per VM)Lightweight (shared OS)
PerformanceLess efficientNear-native
PortabilityLimited (dependent on hypervisor)High (runs anywhere Docker is supported)
Image SizeLarge (GBs)Small (MBs to low GBs)

Docker & Docker Compose Installation.

RHEL-based systems

sudo yum update -y / sudo dnf update -y

sudo yum install docker -y

sudo systemctl start docker

sudo systemctl enable docker

Debian-based systems

sudo apt update -y

sudo apt install docker.io -y

sudo systemctl start docker

sudo systemctl enable docker

Docker-Compose

sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

sudo chmod +x /usr/local/bin/docker-compose

Optional -

sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

Verify Installation -

docker —-version

docker-compose —-version


Docker Commands

docker ps / docker container ls

Purpose: Lists running containers.

Flags:

-a: Show all containers (default shows only running container)

-q: List only container IDs

-s: Shows filesystem size for each container

docker ps                      # docker container ls ## both works same
docker ps -s
docker stop $(docker ps -aq)   # this will stop all runing containers

docker images / docker image ls

Purpose: List local images.

Flags:

-a: Shows all images

-q: Only display image IDs

docker images
docker rmi $(docker images -aq) # this will remove/delete all the local images

docker search <img-name>

Purpose: Search for images on Docker Hub.

Flags:

--limit <number>: Limits the numbers of results.

--filter is-official=true: Shows only official images.

docker search busybox

docker pull <img-name>

Purpose: Download an image from Docker Hub.

docker pull nginx

docker create

Purpose: Create a container from an image (but in stop state, use start command to get it running)

Flags:

--name <container-name>: Assign a name to the container.

-p <host-port>:<container-port>: Bind container port to a port on the host.

-v <host>:<container>: Volume mount.

docker create --name web httpd

docker start <container-id>

Purpose: Start a stopped container.

docker start web

docker stop <container-id>

Purpose: Stop a running container gracefully.

docker stop web

docker rm <container-id>

Purpose: Remove one or more stopped containers.

Flag:

-f: Force removal of a running container.

docker rm web

docker rmi <image-id>

Purpose: Remove one or more Docker images.
Flag:

-f: Force removal even if image is used by containers.

docker rmi httpd

docker run -d

Purpose: Run a container from an image in detached mode (in the background).
Flags:

-d: Run in detached mode.

--name <container-name>: Assign a name to the container.

-p <host-port>:<container-port>: Map Ports.

-v <host>:<container>: Volume mount.

-e <key>:<value>: Set environment variables in the container. If any.

--network <network-name>: Connect the container to a user-defined Docker network.

--restart <policy>: Restart policy. (no, on-failure, always, unless-stopped)

--env-file <file.env>: Load environment variables from a file. (Create a .env file)

--cpus <value>: Limit number of CPUs the container can use.

-m <value>: Set a memory limit for the container (e.g., 512m, 1g).

docker run -d --name database -e MYSQL_ROOT_PASSWORD=12345 mysql
docker run -d --env-file sql.env --name database mysql

docker exec -it <container-id> bash

Purpose: Run a command in a running container (interactively).
Flags:

-i: Interactive Mode.

-t: Allocate a pseudo-TTY/Terminal.

docker exec -it web /bin/bash

docker commit <container-id> <name-image>

Purpose: Create a new image from a container.

docker commit web custom-nginx:v1

docker save -o <file.tar> <img-name:tag>

Purpose: Save an image to a tar archive file.
Flag:

-o <file.tar>: Output filename.

docker save -o nginx.tar nginx:latest

docker load -i <file.tar>

Purpose: Load an image from a tar archive.

Flag:

-i: Input file

docker load -i nginx.tar

docker history <image-id>

Purpose: Show the history of an image.

docker history nginx

docker login -u <username>

Purpose: Authenticate to a Docker registry.

docker login -u user1

docker tag <img-name:tag> <new-name:tag>

Purpose: Tag an image for a specific registry or name.

docker tag nginx:latest myregistry.com/mynginx:prod

docker push

Purpose: Push an image to a registry.

docker push myregistry.com/mynginx:prod

docker network

Purpose: Manage Docker networks.

Sub-Commands:

ls: List docker networks.

create: Create network. (To define type use —driver)

rm: Remove created network.

inspect: To get more details of network.

connect <network-name> <container-name>: Connect network to container.

disconnect <network-name> <container-name>: Disconnect connected network of container.

docker network ls
docker network create frontend --driver bridge       # by default it create a bridge network, even if not specified --driver

docker volume

Purpose: Manage Docker volumes.
Sub-Commands:

ls: List volumes.

create: Create a new volume.

rm: Remove a volume.

inspect: Inspect volume details.

docker volume ls
docker volume create my-volume1             # Named Volume
docker volume inspect my-volume1
docker volume rm my-volume1

docker system prune

Purpose: Remove all unused containers, networks, images, and optionally volumes.
Flags:

-a: Remove all unused images.

-f: Do not prompt for confirmation. / Forcefully.

--volumes: Include volumes in cleanup.

docker system prune -a --volumes -f

docker container inspect <container-id>

Purpose: Display detailed information on a container in JSON format.

docker container inspect web

docker stats <container-id>

Purpose: Display a live stream of resource usage statistics (CPU, memory, network, I/O) for containers.

docker stats web

For More Docker Commands & Options

Official Docker Documentation - https://docs.docker.com/engine/reference/commandline/docker/


Docker Network

Docker network, allows containers to communicate with —each other, host machine, or outside world (internet).

Types of Docker Networks :-

DriverDescription
bridgeThe default network driver.
hostRemove network isolation between the container and the Docker host.
noneCompletely isolate a container from the host and other containers.
overlayOverlay networks connect multiple Docker daemons together.
ipvlanIPvlan networks provide full control over both IPv4 and IPv6 addressing.
macvlanAssign a MAC address to a container.


Docker Volume

A Docker volume is a special type of storage used by Docker containers to store data permanently, even if the container is stopped, deleted, or recreated.

When you run a container, by default, any data it creates is lost when the container stops. Volumes solve this problem by keeping the data outside the container, in a separate location managed by Docker. This makes it easier to save, share, and back up important data.

Types of Docker Volumes :-

Named Volume

• Create and managed by docker

• Stored in Docker’s default location (/var/lib/docker/volumes/)

• Can be reused across multiple containers.

docker volume create my-volume
docker run -d -v my-volume:/app/data my-image
Anonymous Volumes

• Similar to named volumes.

• We don’t name it explicitly. Docker gives it a random name.

• Harder to manage because you don’t control the name. Less flexible.

docker run -d -v /app/data my-image
Bind Mounts

• Links a specific file or folder from host machine into the container.

• Not managed by Docker.

docker run -d -v /host/path:/container/path my-image

This is the default data directory where Docker stores all of its persistent data :-

Images

Containers

Volumes

Networks

So essentially, everything Docker runs or builds is stored here, unless configured.


Dockerfile

A Dockerfile is a text file that contains instructions on how to build a Docker image. Each instruction in the Dockerfile creates a layer in the image.

Basic Structure of a Dockerfile

# Example Dockerfile
FROM nginx
WORKDIR /usr/share/nginx/html
COPY ./html .
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx","-g","daemon off;"]

Build Dockerfile

docker build -t nginx-build .
# if your dockerfile name isn't "Dockerfile"
docker build -f <DockerFile-Name> -t nginx-build .

Dockerfile Attributes/Instruction

InstructionDescriptionExample
FROMSets the base image (must be the first instruction).FROM ubuntu:22.04
LABELAdds metadata to the image (e.g., maintainer, version).LABEL maintainer="@example.com"
ENVSets environment variables.ENV NODE_ENV=production
WORKDIRSets the working directory inside the container.WORKDIR /usr/src/app
COPYCopies files from the host to the container.COPY . /app
ADDSimilar to COPY, but also supports remote URLs and automatic unpacking of compressed files.ADD archive.tar.gz /app/
RUNExecutes a command while building the image (e.g., installing packages).RUN apt-get update && apt-get install
CMDSets the default command to run when the container starts (can be overridden).CMD ["node", "app.js"]
ENTRYPOINTSets the main executable (like CMD, but harder to override).ENTRYPOINT ["python3"]
EXPOSEDocuments the port the container listens on (for reference only).EXPOSE 80
VOLUMECreates a mount point with a volume attached.VOLUME /data
ARGDefines build-time variables (used only during image build).ARG VERSION=1.0.0
USERSets the user that will run inside the container.USER appuser
HEALTHCHECKSets a command to check container health.HEALTHCHECK CMD curl --fail http://localhost
SHELLChanges the default shell used in RUN commands (mostly for Windows images).SHELL ["powershell", "-command"]
ONBUILDTriggers a command in child images (used in base images meant to be extended).ONBUILD RUN npm install
STOPSIGNALSets the system call signal that will be sent to the container to exit.STOPSIGNAL SIGTERM

CMD vs ENTRYPOINT

CMD is default and can be overridden at runtime.

ENTRYPOINT is always executed, and arguments passed at runtime are appended to it


MySQL Dockerfile
FROM mysql:latest
LABEL maintainer="example @example.com"
# COPY init.sql /docker-entrypoint-initdb.d        
EXPOSE 3306
CMD ["mysqld"]

ENV variables that can be used -

ENV MYSQL_ROOT_PASSWORD=12345

ENV MYSQL_DATABASE=Database-name

ENV MYSQL_USER=CreateUser

ENV MYSQL_PASSWORD=PasswordForUser

Initialization SQL Scripts

If you want to run custom .sql files at container startup:
Create .sh or .sql file and COPY it in Docker image.


Postgres Dockerfile
FROM postgres
ENV POSTGRES_USER=root
ENV POSTGRES_PASSWORD=123
ENV POSTGRES_DB=mydatabase
EXPOSE 5432

Build and run -

-docker build -t data-base .

-docker run -d --name pdb data-base

-docker exec -it pdb bash then psql -U root -d mydatabase


MongoDB Dockerfile
FROM mongo
ENV MONGO_INITDB_ROOT_USERNAME=root
ENV MONGO_INITDB_ROOT_PASSWORD=123
ENV MONGO_INITDB_DATABASE=info
EXPOSE 27017

Build and run -

-docker build -t mongodb .

-docker run -d --name mdb mongodb

-docker exec -it mdb mongosh -u root -p


WordPress Dockerfile
FROM mysql:latest
ENV MYSQL_ROOT_PASSWORD=123
ENV MYSQL_DATABASE=Database-name
EXPOSE 3306
CMD ["mysqld"]
FROM wordpress:latest
ENV WORDPRESS_DB_HOST=db
ENV WORDPRESS_DB_NAME=Database-name
ENV WORDPRESS_DB_USER=root
ENV WORDPRESS_DB_PASSWORD=123
EXPOSE 80

Build the files and run them -

-docker build -f <docker-filename> -t <name-the-build> .

-docker run -d --name db <img-name>

-docker run -d -p <port-no>:80 --name <container-name-you-want> --link <continer-name>:<container-img> <img-name>


Node.js Dockerfile

File Structure

node-docker-app/
├── app.js # Node.js app
├── package.json # Dependencies and scripts
└── Dockerfile # Docker build instructions

app.js

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello from Dockerized Node.js App!\n');
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

package.json

{
  "name": "node-docker-app",
  "version": "1.0.0",
  "description": "A simple Node.js app running inside Docker",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "author": "dunoo",
  "license": "ISC"
}

Dockerfile

FROM node
WORKDIR /usr/src/app
COPY package.json .
RUN npm install
COPY app.js .
EXPOSE 3000

Build and run -

-docker build -t nodejs .

-docker run -d -p <port-you-want>:3000 --name node-app nodejs


Python (Flask) Dockerfile

File Structure

flask-docker-app/
├── app.py # Flask application
├── requirements.txt # Python dependencies
└── Dockerfile # Docker instructions

requirements.txt

flask

app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Dockerized Flask App!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

Dockerfile

FROM python
WORKDIR /app
COPY requirement.txt .
RUN pip install --no-cache-dir  -r  requirement.txt
COPY app.py .
EXPOSE 5000
CMD ["python","app.py"]

Build and run -

-docker build -t py-app .

-docker run -d -p 5000:5000 --name py py-app


Docker-Compose

A tool to define and run multi-container Docker applications. Docker compose file are written in YAML (Yet Another Markup Language) extension. (i.e., .yml or .yaml)

Format for file name, docker-compose.yml to configure app’s services.

To run:

docker-compose up -d

Docker Compose Commands

docker-compose --version                  # Displays docker-compose version
docker-compose up -d                      # Start in detached mode
docker-compose down                       # Stop and remove containers, networks, volumes
docker-compose -f composefile.yml up -d   # for file with diffrent name
docker-compose config                     # validates docker-compose.yml file
docker-compose -f composefile.yml config  # same as docker-compose config
docker-compose restart                    # Restart containers
docker-compose logs                       #	View logs of all services
docker-compose up -d --build              # Rebuilds images & starts containers in background

Basic docker-compose.yml Structure

version: '3.9'

services:
  service_name:
    image: or build:
    ports:
    environment:
    volumes:
    depends_on:
    command:
    networks:
    container_name:
networks:
volumes:
DirectiveExample / Description
versionCompose file format version
servicesDefines all containers
imageUse a prebuilt image
buildBuild from a Dockerfile
portsExpose container port to host ("8080:80")
volumesMap host or named volumes to containers ("./data:/app/data")
environmentSet environment variables (- MYSQL_ROOT_PASSWORD=12345) / (MYSQL_ROOT_PASSWORD: “12345”)
commandOverride default command (like CMD in Dockerfile)
depends_onSpecify dependency order (e.g., wait for db before starting app)
networksDefine shared communication networks for services
restartAuto-restart policy: no, always, unless-stopped, on-failure




Portainer

Portainer is a lightweight management UI that allows to easily manage Docker environments (containers, images, networks, volumes, etc.) via a web interface.

docker volume create data
docker run -d -v /var/run/docker.sock:/var/run/docker.sock -v data:/data -p 9000:9000 -p 9443:9443 --name portainer-ui portainer/portainer
# Runs Portainer (a Docker GUI) in detached mode:
#   - Mounts Docker socket to manage Docker.
#   - Stores data in data volume.
#   - Exposes web UI on ports 9000 (HTTP) and 9443 (HTTPS).
#   - Names the container portainer-ui.