πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹
Docker Networking, Volumes, and Compose simplify application deployment, improve scalability, and enhance isolation. They also ensure persistent storage, seamless communication, and reproducible multi-service setups in DevOps workflows.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ“–

πŸ’‘Learning points:

πŸ”Ή Docker Networking – Different network types (bridge, host, overlay), container communication, and linking containers.
πŸ”Ή Docker Volumes – Using volumes and bind mounts to persist data inside containers.
πŸ”Ή Docker Compose – Managing multi-container applications with docker-compose.yml.
πŸ”Ή Port Mapping & Exposing Services – Connecting applications running in different containers.
πŸ”Ή Service Scaling – Running multiple replicas of a service using Compose.

🧠 Learn here:

Mastering Docker: A Comprehensive Guide from Basics to Advanced

Docker Networking

1. Bridge Network (Default)

Bridge networks are the default network type for Docker containers on a single host.

Use Case:

Isolated container-to-container communication on the same Docker host.

Example:

# Create a user-defined bridge network: unlike the default "bridge",
# it gives containers DNS so they can reach each other by name
docker network create my-bridge
docker run -d --name web1 --network my-bridge nginx

# Check IP
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' web1

# Ping by name from another container on the same network
docker run -it --rm --network my-bridge busybox ping -c 3 web1

2. Host Network

Removes the network isolation between container and host β€” container uses host’s network stack directly.

Use Case:

Best for performance-sensitive applications where container ports must match host ports.

Example:

# Run with host network mode (Linux hosts; Docker Desktop needs
# host networking turned on in Settings β†’ Resources β†’ Network)
docker run -d --name web2 --network host nginx

# Nginx runs on the host's port 80
curl http://localhost

3. Overlay Network

Used in Docker Swarm mode to enable multi-host communication.

Use Case:

Connect containers running on different Docker hosts.

Example:

# Initialize swarm
docker swarm init

# Create overlay network
docker network create --driver overlay my_overlay

# Deploy service using that network
docker service create --name web3 --replicas 2 --network my_overlay nginx

Docker Volumes – Using Volumes and Bind Mounts to Persist Data

In Docker, volumes and bind mounts are used to persist data beyond the container's lifecycle.

What are Docker Volumes?

Volumes are managed by Docker and stored in a part of the host filesystem which is managed by Docker (/var/lib/docker/volumes/ on Linux).

Use Case: Recommended way to persist data, especially in production.

Create and Use a Docker Volume

# Create a volume
docker volume create mydata

# Run container with volume
docker run -d \
  --name my-nginx \
  -v mydata:/usr/share/nginx/html \
  nginx

What are Bind Mounts?

Bind mounts allow you to mount a file or directory from the host machine to the container.

Use Case: Useful during development to reflect code changes immediately inside the container.

Run a Container with a Bind Mount

# Run a container using current host directory as a bind mount
docker run -d \
  --name my-nginx-dev \
  -v $(pwd)/site-content:/usr/share/nginx/html \
  nginx

Comparing Volumes and Bind Mounts

Feature Volumes Bind Mounts
Storage Location Managed by Docker Any location on host
Portability Easily portable Tied to host path
Backups Easy using Docker CLI Manual process
Use in Dev/Prod Ideal for production Great for development

Listing and Inspecting Volumes

# List all volumes
docker volume ls

# Inspect volume details
docker volume inspect mydata

Removing Volumes

# Remove unused volumes
docker volume prune

# Remove specific volume
docker volume rm mydata
πŸ’‘ Tip: Prefer volumes over bind mounts for long-term and secure storage.

This setup ensures your application data survives container restarts, upgrades, and rebuilds.


Docker Compose – Managing Multi-Container Applications

Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application's services, networks, and volumes, and then with a single command (docker compose up), you can start all services as defined.

Why Use Docker Compose?

  • Simplifies multi-container setups
  • Enables declarative configuration
  • Easy to replicate environments (dev, staging, prod)
  • Convenient local development

docker-compose.yml Structure

services:
  web:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - ./html:/usr/share/nginx/html

  app:
    image: node:24
    working_dir: /app
    volumes:
      - ./app:/app
    command: node server.js
    depends_on:
      - db

  db:
    image: postgres:15
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: appdb
    volumes:
      - db-data:/var/lib/postgresql/data

volumes:
  db-data:

Explanation:

  • web: Uses NGINX to serve static files from ./html directory.
  • app: A Node.js application container depending on db.
  • db: PostgreSQL container with environment variables and persistent volume db-data.

Common Commands

# Start all containers as defined
docker compose up

# Start in detached mode
docker compose up -d

# Stop all containers
docker compose down

# Rebuild services
docker compose up --build

# View logs
docker compose logs -f

Example Use Case

A web application stack where:

  • NGINX serves frontend
  • Node.js handles backend logic
  • PostgreSQL is the database backend

    All orchestrated using Docker Compose for easy setup, testing, and teardown.

Docker Compose is ideal for development environments and small-scale deployments, helping DevOps and developers define infrastructure as code in a simple and repeatable way.


Docker Service Scaling – Running Multiple Replicas with Docker Compose

Docker Compose allows you to scale your services easily using the --scale flag. This is particularly useful for simulating load-balanced environments or building resilient applications.

Sample docker-compose.yml

services:
  web:
    image: nginx:alpine
    ports:
      - "80"   # container port only: Docker picks a free host port for each replica

Scaling the Service

Use the --scale flag to run multiple replicas of the service:

docker compose up --scale web=3 -d

This command launches 3 containers of the web service.

Verifying the Running Containers

docker ps

You will see three containers with the same image nginx:alpine but different container IDs and names.

Load Balancing

To enable actual load balancing across replicas, you can:

  • Use a reverse proxy like Traefik or NGINX
  • Or use Docker Swarm which handles service discovery and load balancing

Stopping and Removing Services

docker compose down

This command stops and removes all scaled containers and network created by Compose.

Notes

  • --scale works with or without -d; publish only the container port (or none), otherwise the replicas fight over one host port.
  • You can only scale stateless services reliably; scaling a database container without clustering isn't advised.

πŸ“šοΈ Resources:

πŸ“Œ Docker Networking – Docker Docs
πŸ“Œ Docker Volumes – Persistent Storage
πŸ“Œ Docker Compose Basics – Compose Guide
πŸ“Œ Networking in Containers – Bridge & Overlay Networks


Initial Tasks:

βœ… Task 1: Inspect the default Docker network and list all networks:

docker network ls

βœ… Task 2: Install Docker Compose (Guide).

πŸ”₯ Challenges

 
πŸ”ΉChallenge 1: Create a custom bridge network and connect two containers (alpine and nginx).
πŸ”Ή Challenge 2: Run a MySQL container with a named volume (mysql_data) and confirm data persistence after container restart.
πŸ”Ή Challenge 3: Create a docker-compose.yml file to launch a Flask API and a PostgreSQL database together.
πŸ”Ή Challenge 4: Implement environment variables in your Docker Compose file to configure database credentials securely.
πŸ”Ή Challenge 5: Deploy a WordPress site using Docker Compose (WordPress + MySQL).
πŸ”Ή Challenge 6: Create a multi-container setup where an Nginx container acts as a reverse proxy for a backend service.
πŸ”Ή Challenge 7: Set up a network alias for a database container and connect an application container to it.
πŸ”Ή Challenge 8: Use docker inspect to check the assigned IP address of a running container and communicate with it manually.
πŸ”Ή Challenge 9: Deploy a Redis-based caching system using Docker Compose with a Python or Node.js app.
πŸ”Ή Challenge 10: Implement container health checks in Docker Compose (healthcheck: section).

βœ… Solutions

 
βœ… Challenge 1: Create a custom bridge network and connect two containers (alpine and nginx).

Step 1: Create a Custom Bridge Network

docker network create my-custom-network

Step 2: Run an Nginx Container on the Custom Network

docker run -d --name nginx-container --network my-custom-network nginx

Step 3: Run an Alpine Container on the Same Network

docker run -it --rm --name alpine-container --network my-custom-network alpine sh

Step 4: Test Connectivity from Alpine to Nginx

apk add --no-cache curl
curl nginx-container

Step 5: Verify Network Connection

docker network ls
docker network inspect my-custom-network

βœ… Challenge 2: Run a MySQL container with a named volume and confirm data persistence

Step 1: Create a Named Volume

docker volume create mysql_data

Step 2: Run MySQL with the Named Volume

docker run -d --name mysql-container \
  -e MYSQL_ROOT_PASSWORD=rootpass \
  -e MYSQL_DATABASE=mydb \
  -v mysql_data:/var/lib/mysql \
  -p 3306:3306 \
  mysql:8.4

Step 3: Verify Data Persistence

until docker exec mysql-container mysqladmin ping -uroot -prootpass --silent; do sleep 2; done   # wait for MySQL to start
docker exec -it mysql-container mysql -uroot -prootpass -e "CREATE TABLE mydb.users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50));"
docker exec -it mysql-container mysql -uroot -prootpass -e "INSERT INTO mydb.users (name) VALUES ('Alice'), ('Bob');"
docker exec -it mysql-container mysql -uroot -prootpass -e "SELECT * FROM mydb.users;"

Step 4: Restart and Verify

docker stop mysql-container
docker rm mysql-container
docker run -d --name mysql-container \
  -e MYSQL_ROOT_PASSWORD=rootpass \
  -e MYSQL_DATABASE=mydb \
  -v mysql_data:/var/lib/mysql \
  -p 3306:3306 \
  mysql:8.4
until docker exec mysql-container mysqladmin ping -uroot -prootpass --silent; do sleep 2; done   # wait for MySQL to start
docker exec -it mysql-container mysql -uroot -prootpass -e "SELECT * FROM mydb.users;"

βœ… Challenge 3: docker-compose.yml for Flask API and PostgreSQL

Step 1: app.py

from flask import Flask
import psycopg2

app = Flask(__name__)

@app.route("/")
def home():
    return "πŸš€ Flask API with PostgreSQL is running!"

@app.route("/db-status")
def db_status():
    try:
        conn = psycopg2.connect(dbname="mydb", user="postgres", password="postgres", host="db")
        conn.close()
        return "βœ… PostgreSQL is connected!"
    except Exception as e:
        return f"❌ Database connection failed: {e}"

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

Step 2: requirements.txt

flask
psycopg2-binary

Step 3: Dockerfile

FROM python:3.13
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]

Step 4: docker-compose.yml

services:
  flask-app:
    build: .
    container_name: flask-container
    ports:
      - "5000:5000"
    depends_on:
      - db
    environment:
      DATABASE_URL: "postgresql://postgres:postgres@db:5432/mydb"

  db:
    image: postgres:17
    container_name: postgres-container
    environment:
      POSTGRES_DB: mydb
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Step 5: Start the Stack

docker compose up -d

Step 6: Test

curl http://localhost:5000/
curl http://localhost:5000/db-status

βœ… Challenge 4: Secure credentials using environment variables

Step 1: .env

POSTGRES_DB=mydb
POSTGRES_USER=postgres
POSTGRES_PASSWORD=supersecurepassword

Step 2: Modified docker-compose.yml

services:
  flask-app:
    build: .
    container_name: flask-container
    ports:
      - "5000:5000"
    depends_on:
      - db
    env_file:
      - .env
    environment:
      DATABASE_URL: "postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}"

  db:
    image: postgres:17
    container_name: postgres-container
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    env_file:
      - .env

volumes:
  postgres_data:

Step 3: Updated app.py

import os
import psycopg2
from flask import Flask

app = Flask(__name__)

DB_NAME = os.getenv("POSTGRES_DB", "default_db")
DB_USER = os.getenv("POSTGRES_USER", "default_user")
DB_PASSWORD = os.getenv("POSTGRES_PASSWORD", "default_pass")
DB_HOST = "db"

@app.route("/")
def home():
    return "πŸš€ Flask API with PostgreSQL using .env is running!"

@app.route("/db-status")
def db_status():
    try:
        conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST)
        conn.close()
        return "βœ… PostgreSQL is connected!"
    except Exception as e:
        return f"❌ Database connection failed: {e}"

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

Step 4: Rebuild and Start

docker compose up -d --build

Step 5: Verify

curl http://localhost:5000/
curl http://localhost:5000/db-status
docker exec -it flask-container env | grep POSTGRES

Bonus: Add .env to .gitignore

echo ".env" >> .gitignore


βœ… Challenge 5: Deploy a WordPress site using Docker Compose (WordPress + MySQL)

Step 1: Create a .env File

# MySQL Database Credentials
MYSQL_ROOT_PASSWORD=rootpassword
MYSQL_DATABASE=wordpress
MYSQL_USER=wordpressuser
MYSQL_PASSWORD=wordpresspass

# WordPress Configuration
WORDPRESS_DB_HOST=db
WORDPRESS_DB_USER=wordpressuser
WORDPRESS_DB_PASSWORD=wordpresspass
WORDPRESS_DB_NAME=wordpress

Step 2: Create the docker-compose.yml File

services:
  wordpress:
    image: wordpress:latest
    container_name: wordpress-container
    restart: always
    depends_on:
      - db
    ports:
      - "8080:80"
    environment:
      WORDPRESS_DB_HOST: ${WORDPRESS_DB_HOST}
      WORDPRESS_DB_USER: ${WORDPRESS_DB_USER}
      WORDPRESS_DB_PASSWORD: ${WORDPRESS_DB_PASSWORD}
      WORDPRESS_DB_NAME: ${WORDPRESS_DB_NAME}
    env_file:
      - .env
    volumes:
      - wordpress_data:/var/www/html

  db:
    image: mysql:8.4
    container_name: mysql-container
    restart: always
    ports:
      - "3306:3306"
    env_file:
      - .env
    volumes:
      - mysql_data:/var/lib/mysql

volumes:
  wordpress_data:
  mysql_data:

Step 3: Start WordPress + MySQL

docker compose up -d

Step 4: Access WordPress

Open http://localhost:8080 in your browser.

Step 5: Verify Containers

docker ps

βœ… Challenge 6: Reverse Proxy with Nginx for Flask

Step 1: app.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "πŸš€ Flask API is running behind Nginx!"

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

Step 2: requirements.txt

flask

Step 3: Dockerfile

FROM python:3.13
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]

Step 4: nginx.conf

server {
    listen 80;
    location / {
        proxy_pass http://backend:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Step 5: docker-compose.yml

services:
  nginx:
    image: nginx:latest
    container_name: nginx-proxy
    ports:
      - "8080:80"
    depends_on:
      - backend
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf
    restart: always

  backend:
    build: .
    container_name: flask-backend
    expose:
      - "5000"
    restart: always

Step 6: Build and Run

docker compose up -d --build

Step 7: Test

curl http://localhost:8080

βœ… Challenge 7: Network Alias for DB Access

Step 1: app.py

import os
import psycopg2
from flask import Flask

app = Flask(__name__)

DB_HOST = os.getenv("DB_HOST", "db-alias")
DB_NAME = os.getenv("POSTGRES_DB", "mydb")
DB_USER = os.getenv("POSTGRES_USER", "postgres")
DB_PASSWORD = os.getenv("POSTGRES_PASSWORD", "postgres")

@app.route("/")
def home():
    return "πŸš€ Flask API connected to PostgreSQL using network alias!"

@app.route("/db-status")
def db_status():
    try:
        conn = psycopg2.connect(
            dbname=DB_NAME, user=DB_USER,
            password=DB_PASSWORD, host=DB_HOST
        )
        conn.close()
        return "βœ… PostgreSQL is connected via alias!"
    except Exception as e:
        return f"❌ Database connection failed: {e}"

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

Step 2: requirements.txt

flask
psycopg2-binary

Step 3: Dockerfile

FROM python:3.13
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]

Step 4: .env

POSTGRES_DB=mydb
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres
DB_HOST=db-alias

Step 5: docker-compose.yml

services:
  flask-app:
    build: .
    container_name: flask-container
    ports:
      - "5000:5000"
    depends_on:
      - db
    environment:
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      DB_HOST: db-alias
    networks:
      mynetwork:
        aliases:
          - app-alias

  db:
    image: postgres:17
    container_name: postgres-container
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      mynetwork:
        aliases:
          - db-alias

volumes:
  postgres_data:

networks:
  mynetwork:

Step 6: Build and Run

docker compose up -d --build

Step 7: Verify

curl http://localhost:5000/
curl http://localhost:5000/db-status
docker network inspect mynetwork


βœ… Challenge 8: Inspect Container IP and Access via IP

Step 1: Run an Nginx Container

docker run -d --name my-nginx -p 8080:80 nginx

Step 2: Get Internal IP Address

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-nginx

Step 3: Access via Internal IP

curl http://<container_ip>
# Works from a Linux host. Docker Desktop runs containers in a VM, so from macOS/Windows use:
# docker run --rm curlimages/curl http://<container_ip>

Example Output:

<!DOCTYPE html>
<html>
<head><title>Welcome to nginx!</title></head>
<body>
<h1>Welcome to nginx!</h1>
</body>
</html>

Step 4: Validate Network Info

docker network inspect bridge

βœ… Challenge 9: Redis-Based Caching with Python (Flask)

Step 1: app.py

import os
import redis
from flask import Flask

app = Flask(__name__)
redis_host = os.getenv("REDIS_HOST", "redis")
redis_client = redis.Redis(host=redis_host, port=6379, db=0)

@app.route("/")
def home():
    redis_client.incr("visits")
    visits = redis_client.get("visits").decode("utf-8")
    return f"πŸš€ Flask + Redis! Visit count: {visits}"

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

Step 2: requirements.txt

flask
redis

Step 3: Dockerfile

FROM python:3.13
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
EXPOSE 5000
CMD ["python", "app.py"]

Step 4: docker-compose.yml

services:
  flask-app:
    build: .
    container_name: flask-container
    ports:
      - "5000:5000"
    depends_on:
      - redis
    environment:
      REDIS_HOST: redis
    restart: always

  redis:
    image: redis:latest
    container_name: redis-cache
    ports:
      - "6379:6379"
    restart: always

Step 5: Run the Setup

docker compose up -d --build

Step 6: Test It

curl http://localhost:5000

Step 7: Tear Down

docker compose down -v

βœ… Challenge 10: Docker Compose Health Checks

Step 1: app.py

from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
    return "πŸš€ Flask API is running!"

@app.route("/health")
def health():
    return "βœ… OK", 200

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

Step 2: Dockerfile

FROM python:3.13
WORKDIR /app
COPY . .
RUN pip install flask
EXPOSE 5000
CMD ["python", "app.py"]

Step 3: docker-compose.yml with Health Checks

services:
  flask-app:
    build: .
    container_name: flask-container
    ports:
      - "5000:5000"
    restart: always
    depends_on:
      redis:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:5000/health"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 5s

  redis:
    image: redis:latest
    container_name: redis-cache
    ports:
      - "6379:6379"
    restart: always
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 5s

Step 4: Run with Health Check

docker compose up -d --build

Step 5: Check Health

docker ps

Step 6: Inspect Detailed Status

docker inspect --format='{{json .State.Health}}' flask-container | jq
Bonus πŸ’‘ Restart Unhealthy Containers Automatically

Docker Engine doesn't restart a container just because it is unhealthy: restart policies only react to the main process exiting (Swarm services, by contrast, replace unhealthy tasks). A common workaround is to let a failed check stop the app so the restart policy takes over:

services:
  flask-app:
    build: .
    container_name: flask-container
    ports:
      - "5000:5000"
    init: true                 # run a tiny init as PID 1 so the app can be signalled
    restart: unless-stopped    # restarts the container whenever its process exits
    depends_on:
      redis:
        condition: service_healthy
    healthcheck:
      # a failed check stops the app; the restart policy then brings it back
      test: ["CMD-SHELL", "curl -fsS http://localhost:5000/health || kill 1"]
      interval: 10s
      timeout: 5s
      retries: 3
      start_period: 5s

  redis:
    image: redis:latest
    container_name: redis-cache
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 5s

How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das) and use #60DaysOfDevOps to engage with the community!


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post