Skip to content

Advanced Topics

1️⃣ Docker Build Optimization

Example: Bad vs Good Dockerfile

❌ Bad (breaks cache every build)

COPY . .
RUN npm install
````

 Good (uses layer caching)

```Dockerfile
COPY package*.json ./
RUN npm install
COPY . .

Commands

docker build -t app .
docker build --no-cache -t app .
docker history app

Docs


2️⃣ CMD vs ENTRYPOINT

Example

ENTRYPOINT ["node"]
CMD ["server.js"]

Override CMD:

docker run app other.js

Inspect configuration:

docker inspect app | grep -A5 Cmd

Docs


3️⃣ Environment Variables & Secrets

Example

docker run -e DB_HOST=localhost app
docker run --env-file .env app

❌ Avoid hardcoding secrets:

ENV DB_PASSWORD=secret

Docs


4️⃣ Multiple Docker Compose Files

Example

docker compose -f docker-compose.yml -f docker-compose.dev.yml up

Docs


5️⃣ Docker Networking (Deep)

Example

docker network create app-net
docker run --network app-net --name api api-image
docker run --network app-net frontend-image

Service-to-service access:

http://api:3000

Commands

docker network ls
docker network inspect app-net

Docs


6️⃣ Volumes vs Bind Mounts

Volume (Persistent)

docker volume create dbdata
docker run -v dbdata:/var/lib/postgresql/data postgres

Bind Mount (Development)

docker run -v $(pwd):/app app

Docs


7️⃣ Docker Security

Run as Non-Root

RUN adduser --disabled-password appuser
USER appuser

Read-Only Filesystem

docker run --read-only app

Docs


8️⃣ Resource Management

Limit Resources

docker run --memory=512m --cpus=1 app

Monitor Usage

docker stats

Docs


9️⃣ Health Checks

Dockerfile

HEALTHCHECK CMD curl -f http://localhost:3000 || exit 1

Inspect

docker inspect container | grep Health -A10

Docs


🔟 Docker in CI/CD (GitHub Actions Example)

Example

- name: Build Image
  run: docker build -t myapp .

- name: Push Image
  run: docker push myrepo/myapp

Docs


1️⃣1️⃣ Docker Registry

Tag & Push

docker tag app myrepo/app:v1
docker push myrepo/app:v1

Docs


1️⃣2️⃣ Docker-in-Docker vs Docker Socket

Docker Socket (Preferred)

docker run -v /var/run/docker.sock:/var/run/docker.sock docker

⚠ Gives full control over host Docker.

Docker-in-Docker

docker run --privileged docker:dind

Docs


1️⃣3️⃣ Logging & Observability

Logs

docker logs container

Inspect Logging Driver

docker inspect container | grep LogConfig -A5

Docs


1️⃣4️⃣ Debugging Containers

Exec vs Attach

docker exec -it container bash
docker attach container

Inspect Image Layers

docker history image

Docs


1️⃣5️⃣ Multi-Architecture Images

Build Multi-Arch Image

docker buildx build --platform linux/amd64,linux/arm64 -t app .

Docs


1️⃣6️⃣ Docker → Kubernetes Transition

Why Kubernetes?

  • Auto scaling
  • Self-healing
  • Service discovery

Docs


Dockerfile
→ Docker Compose
→ Security
→ CI/CD
→ Observability
→ Kubernetes

✅ Final Notes

By practicing the examples in this document, you will:

  • Understand Docker deeply
  • Be production-ready
  • Confidently face DevOps interviews