DevopsIntermediate

The Role of Containers in DevOps: Docker and Beyond

DeveloperHat Team
8 min read

TL;DR

Explore how containers revolutionize DevOps practices and learn best practices for container orchestration.

The Role of Containers in DevOps: Docker and Beyond

Executive Summary

Containers package an application with its dependencies into a portable image that runs the same way on a laptop, a CI runner, and a production node. That consistency is their contribution to DevOps: the environment stops being a variable in every bug report and deployment. This guide covers how containers differ from virtual machines, image construction with multi-stage Dockerfiles, local development with Compose, the path from a single container to orchestration with Kubernetes, networking and storage fundamentals, and the security and CI/CD practices that make containers safe to standardise on. After reading it, you should be able to containerise a service properly and judge how much orchestration your estate actually needs.

Why This Matters

Before containers, "works on my machine" was a structural problem: development, testing, and production environments drifted, and deployment meant re-creating an environment by hand and hoping. Containers collapse that drift by shipping the environment with the application. The failure mode has moved rather than vanished: teams now ship bloated images with build tools and secrets baked in, run everything as root, deploy mutable tags nobody can trace, and adopt Kubernetes for three containers. Each of those mistakes converts the portability win into security exposure and operational drag, which is why the practices in this guide matter as much as the technology.

Core Concepts

Containers versus Virtual Machines

A virtual machine virtualises hardware and runs a full guest operating system per workload. A container shares the host kernel and isolates a process using Linux namespaces (for visibility) and cgroups (for resource limits). The consequences are practical: containers start in milliseconds to seconds, carry megabytes rather than gigabytes of overhead, and pack densely on a host, but they share a kernel, so the isolation boundary is weaker than a hypervisor's and a Linux container cannot run a Windows workload. Choose VMs where strong isolation or a different OS is the requirement, containers where density, speed, and environment consistency are.

Building Images: Layers and Multi-Stage Builds

An image is a stack of read-only layers, one per Dockerfile instruction, cached and reused between builds. Ordering instructions from least to most frequently changed keeps the cache effective. The production pattern is the multi-stage build: compile in a stage that has the toolchain, then copy only the artefacts into a minimal runtime image:

# Optimized Dockerfile
FROM node:18-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=deps /app/node_modules ./node_modules
USER node
CMD ["node", "dist/main.js"]

Note the disciplines embedded in that file: a small Alpine base, production dependencies only in the final image, a non-root USER, and no secrets anywhere (build-time secrets need BuildKit secret mounts, not ENV or ARG, which persist in image history).

Local Development with Compose

Docker Compose runs a multi-container application from one YAML file, which makes it the standard local development and integration-test environment: the application and its database start together, wired by service-name DNS, with named volumes preserving data between runs:

# docker-compose.yml
version: '3.8'

services:
  web:
    build: .
    ports:
      - "3000:80"
    environment:
      NODE_ENV: production
    depends_on:
      - db

  db:
    image: postgres:13
    volumes:
      - db_data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${DB_PASSWORD}

volumes:
  db_data:

Compose is a development and small-deployment tool. It has no self-healing across hosts, no rolling updates, and no autoscaling; those are the problems orchestration exists to solve.

From Containers to Orchestration

When containers run in production at any scale, an orchestrator (in practice, usually Kubernetes) takes over placement, restart, scaling, and service discovery. The core objects mirror the concepts you already know: a Deployment keeps a declared number of replicas running and rolls out changes, and a Service gives them a stable endpoint:

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - name: web
        image: web-app:1.0.0
        ports:
        - containerPort: 80
        resources:
          limits:
            cpu: "1"
            memory: "512Mi"
          requests:
            cpu: "0.5"
            memory: "256Mi"

# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: web-service
spec:
  selector:
    app: web
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: LoadBalancer

The pinned tag (web-app:1.0.0, never a floating latest) is what makes a deployment reproducible and a rollback meaningful.

Networking and Storage

Container networking has three common shapes: bridge networks for container-to-container communication on one host, host networking that shares the host's stack for maximum performance at the cost of isolation, and overlay networks that span hosts. In Kubernetes, NetworkPolicies act as firewalls between pods and should default to denying traffic that is not explicitly required:

# network-policy.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-network-policy
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: web
      ports:
        - protocol: TCP
          port: 8080

For storage, containers are ephemeral by design: anything written outside a volume dies with the container. Use volumes for data that must persist, bind mounts for configuration and local development, and in Kubernetes, PersistentVolumeClaims backed by storage classes matched to the workload's performance and sharing needs.

Containers in CI/CD

The delivery pipeline is where container discipline pays off. Build the image once in CI, tag it with the commit SHA, scan it, push it to a registry, and deploy that immutable artefact through every environment:

# GitHub Actions workflow
name: Container Build

on:
  push:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            myregistry.azurecr.io/myapp:${{ github.sha }}

Collect logs from container stdout and stderr (never from files inside containers) and scrape metrics from orchestrator and application endpoints; observability designed around ephemeral containers is the only kind that survives them.

Decision Framework

SituationRecommendation
Local development of a multi-service appDocker Compose
One or two services in production, small teamA managed container service (ECS Fargate, Cloud Run, Azure Container Apps)
Many services, scaling and self-healing requirementsKubernetes, managed where possible
Strong isolation or non-Linux workloads requiredVirtual machines, or containers inside VMs
Image size or build time is a problemMulti-stage builds, smaller bases, layer-order discipline
Stateful workload with strict storage needsManaged data service outside the orchestrator, containers for the stateless tiers

Implementation Checklist

  • [ ] Images built with multi-stage Dockerfiles from minimal, official base images
  • [ ] Containers run as a non-root user with resource requests and limits set
  • [ ] No secrets in images or Dockerfiles; build secrets passed via BuildKit secret mounts
  • [ ] Images tagged immutably (commit SHA or version) and scanned in CI before push
  • [ ] Local development reproducible from a committed Compose file
  • [ ] Network policies restrict traffic between services to required paths
  • [ ] Persistent data lives in volumes or managed services, never in container filesystems
  • [ ] Logs written to stdout/stderr and collected centrally
  • Trade-offs

    Containers trade isolation strength for efficiency: a shared kernel is a shared failure and attack surface, mitigated rather than eliminated by user namespaces, seccomp, and runtime hardening. Image-based delivery shifts work into build pipelines and registries that must themselves be secured and maintained. Orchestration solves production problems while creating a platform to operate. And the ecosystem moves quickly: base images, runtimes, and best practices age, so an unmaintained container estate accumulates vulnerabilities exactly like an unpatched server estate did.

    When Not to Use

  • Workloads needing a different kernel or OS than the host: use virtual machines.
  • Deeply stateful systems your team is not ready to run in containers: keep the database on a managed service or VM while containerising the stateless parts.
  • Kubernetes for a single small service: the operational cost exceeds the benefit; a managed container service or even a VM with Compose is proportionate.
  • Packaging a monolith unchanged and expecting microservice benefits: containerising a legacy application is a valid migration step, but the benefits arrive with the operational practices, not the Dockerfile alone.
  • Conclusion

    Containers earn their place in DevOps by making environments reproducible and deployments artefacts instead of procedures. The technology is the easy half; the returns come from the disciplines around it: minimal non-root images, immutable tags, scanning, declarative orchestration scaled to the actual problem, and observability built for ephemeral workloads. Adopt those, and containers simplify delivery instead of relocating its complexity.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.