# Deploying containers: PaaS, Docker Swarm and Kubernetes

Take the image you built to production: hand it to a platform that runs it for you, spread it across machines with Docker Swarm, or move to Kubernetes, and know which fits your team.

Course: [Docker](https://devops.rajeev.pro/courses/docker), lesson 14. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/docker/14-deploying-containers

## What you will learn

- Compare one server with Compose, a PaaS, Docker Swarm and Kubernetes by what you must operate
- Deploy an image to a container platform, giving it the port, configuration and health check it needs
- Run replicated services with Docker Swarm, with rolling updates and self-healing
- Map Docker and Compose ideas onto Kubernetes objects
- Check an image is ready for any platform before deploying it

## Same image, four homes

So far, you've built one image and pushed it to a registry. Running that same image on every server by hand makes
updates and recovery depend on a person being available. A deployment platform keeps the image reference but takes
on some of the work of starting, replacing and scaling containers. The trade-off is how much control you want
versus how much infrastructure you want to operate. In this lesson, you'll compare a platform, Swarm and
Kubernetes, then run a small Swarm service and observe its desired state.

> **Figure.** Four ways to run containers in production, from least to most to operate. One server with Docker and Compose: you run the VM, Docker, updates and backups; good for side projects and internal tools. PaaS or serverless containers such as Cloud Run, App Runner, Fly.io and Render: you provide only the image and scaling is automatic; good for web apps, APIs and small teams. Docker Swarm: a few nodes with replicas, rolling updates and self-healing; good for small clusters. Kubernetes on EKS, GKE, AKS or k3s: scales to anything; good for many services and platform teams.
>
> The image doesn't change. Who keeps it running does.

**One server with Compose** (lesson 9) is where many products start: `docker compose pull && docker compose
up -d` on a VM, restart policies, backups of the volumes. It's cheap and easy to understand. Its limit: one
machine is one failure, and a deploy restarts containers on it.

## Platforms that run it for you

Platforms such as **Google Cloud Run**, **AWS App Runner**, **ECS on Fargate**, **Azure Container Apps**, **Fly.io**
and **Render** accept an image and run it. Depending on the service, they can manage TLS, load balancing, scaling,
restarts and logs. You still provide:

- an image reference and registry credentials. Prefer a digest or SHA tag (lesson 8).
- the listening port. Many platforms set a `PORT` variable; read it instead of hard-coding 8080.
- configuration and secrets through platform settings, not inside the image (lesson 11).
- a health-check path such as `/health`. It helps the platform detect a bad release.
- CPU, memory and instance limits. These affect both performance and the bill.

The application contract stays familiar across platforms. Log to stdout. Keep durable state in a database or
object store, not the container's disk. Start quickly and handle SIGTERM so the process can exit cleanly when
the platform replaces it. The platform can restart a process, but it cannot make an app stateless or safe by
itself. Those choices remain yours.

> **Video.** [Google Cloud Run (GCR) vs Azure Container Instances (ACI) vs AWS ECS with Fargate](https://www.youtube.com/watch?v=Jq8MY1ZGjno) (DevOps & AI Toolkit)

## Docker Swarm

**Swarm mode** is built into Docker: it turns several machines into one cluster and runs **services**, each with
a number of replicas. On one machine you can try it in a minute:

```sh
$ docker swarm init --advertise-addr 127.0.0.1
Swarm initialized: current node (ucnmsfuxg904oob5mjus3gxm3) is now a manager.
$ docker service create -d --name api --replicas 3 -p 8090:8080 -e APP_VERSION=1.0.0 price-api:multi
$ docker service ls
NAME      MODE         REPLICAS   IMAGE             PORTS
api       replicated   3/3        price-api:multi   *:8090->8080/tcp
```

A **rolling update** replaces replicas one at a time:

```sh
$ docker service update --env-add APP_VERSION=1.1.0 --update-parallelism 1 --update-delay 2s api
$ docker service ps api --format 'table {{.Name}}\t{{.CurrentState}}\t{{.DesiredState}}'
NAME        CURRENT STATE             DESIRED STATE
api.1       Running 20 seconds ago    Running
 \_ api.1   Shutdown 21 seconds ago   Shutdown
api.2       Running 7 seconds ago     Running
 \_ api.2   Shutdown 8 seconds ago    Shutdown
api.3       Running 14 seconds ago    Running
 \_ api.3   Shutdown 15 seconds ago   Shutdown
```

And it heals itself. Kill one replica's container and the manager starts a new one, because three are desired:

```sh
$ docker rm -f $(docker ps -q --filter name=api.1)
$ docker service ps api --filter desired-state=running --format '{{.Name}} {{.CurrentState}}'
api.1 Running less than a second ago
api.2 Running 15 seconds ago
api.3 Running 22 seconds ago
$ docker service rm api && docker swarm leave --force
```

Other machines join with the `docker swarm join` command that `init` prints, and `docker stack deploy -c
compose.yaml shop` runs a Compose file across the cluster, with the `deploy:` section setting replicas and update
order. Swarm is simple and needs little more than Docker skills, but its ecosystem is small; most teams that
outgrow one server go to a platform or to Kubernetes.

The manager stores the desired number of replicas and schedules tasks on cluster nodes. If one task stops, the
manager compares the current state with that desired count and starts a replacement. During a rolling update,
parallelism controls how many replicas change at once; a delay gives you time to observe each batch. These
settings trade speed for a smaller blast radius. Swarm is useful when a small team wants basic scheduling with
familiar Docker commands. It is not a reason to operate a cluster if a managed platform already meets the need.

## Kubernetes

**Kubernetes** is the industry's standard orchestrator: the same idea of desired state and self-healing, with
far more features and far more to learn. Your Docker knowledge maps straight onto it:

| Docker / Compose              | Kubernetes                                                  |
| ----------------------------- | ----------------------------------------------------------- |
| a container                   | a container in a **Pod**                                    |
| a service with `replicas: 3`  | a **Deployment**                                            |
| a service name in DNS         | a **Service**                                               |
| published port, reverse proxy | a Service of type LoadBalancer, or an **Ingress** / Gateway |
| `environment:`, `secrets:`    | a **ConfigMap**, a **Secret**                               |
| a named volume                | a **PersistentVolumeClaim**                                 |
| `healthcheck:`                | liveness and readiness **probes**                           |
| `mem_limit`, `cpus`           | `resources.requests` and `limits`                           |

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 3
  selector:
    matchLabels: { app: api }
  template:
    metadata:
      labels: { app: api }
    spec:
      containers:
        - name: api
          image: ghcr.io/acme/price-api:sha-3f9c2e1
          ports: [{ containerPort: 8080 }]
          readinessProbe:
            httpGet: { path: /health, port: 8080 }
          resources:
            limits: { memory: 256Mi, cpu: 500m }
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: [ALL] }
```

Every hardening flag from lesson 11 has a field here. Managed services (EKS, GKE, AKS) run the control plane
for you; k3s is a light distribution for small clusters and labs. The Kubernetes course on this site starts
where this lesson ends.

Kubernetes describes desired state in API objects. A Deployment asks for replicas; the controller creates
Pods and replaces them when they fail. A Service gives those Pods a stable network name, while readiness probes
decide whether a Pod should receive traffic. Requests and limits communicate resource needs and caps to the
scheduler and runtime. This model scales across many machines, but it brings more objects, permissions and
upgrades to manage. Learn the smallest slice needed for your job before adopting the whole ecosystem. If one
server or a managed container platform meets the requirement, Kubernetes may add operational work without
adding value.

> **Choosing.** Start with the least you have to operate: a platform, or one server with Compose and good backups. Move to an orchestrator when you have many services, need zero-downtime deploys across machines, or a team to run it. Whatever you pick, deploy immutable images by digest or SHA tag, with health checks, limits and a rollback you've tried.

> **Video.** [Docker vs Kubernetes vs Docker Swarm | Comparison in 5 mins](https://www.youtube.com/watch?v=9_s3h_GVzZc&t=38s) (TechWorld with Nana)

## Swarm stacks, secrets and rolling updates

`docker stack deploy` turns a Compose-shaped file into Swarm services. A Swarm secret is mounted under
`/run/secrets`, not put in an image or command line. Rolling-update settings control parallelism and rollback.

The stack file describes the services and their desired settings. Swarm compares that declaration with the
running tasks, then replaces tasks when the image or configuration changes. A secret is stored and distributed
through Swarm's secret mechanism, then mounted only into services that request it. This is safer than placing
the value in an environment variable or command line, where it can appear in inspection output or logs. A
rolling update replaces a limited batch at a time; rollback settings define what happens if that update fails.
Keep a health check that reflects application readiness, and verify the new replicas before removing the old
ones.

```yaml
services:
  api:
    image: price-api:multi
    deploy:
      replicas: 3
      update_config: {parallelism: 1, delay: 5s, order: start-first}
      rollback_config: {parallelism: 1}
secrets:
  api_token: {external: true}
```

```sh
$ printf 'local-demo-token' | docker secret create api_token -
$ docker stack deploy -c stack.yml academy
$ docker service ls
$ docker service update --rollback academy_api
$ docker stack rm academy && docker secret rm api_token
```

## Mission: Self-healing replicas on your laptop

Turn your Docker into a one-node swarm, run the price API with three replicas, roll out a new version one replica at a time, kill a replica and watch it come back, then leave the swarm.

- You need: Docker and the price-api:multi image from lesson 7
- You'll have: 3/3 replicas, a completed rolling update, a replaced replica, and plain Docker again

```sh
$ docker swarm init --advertise-addr 127.0.0.1
$ docker service create -d --name api --replicas 3 -e APP_VERSION=1.0.0 price-api:multi
$ docker service ls --format '{{.Name}} {{.Replicas}}'
api 3/3
$ docker service update --env-add APP_VERSION=1.1.0 --update-parallelism 1 --update-delay 2s api
$ docker service ps api                     # each replica: one Running, one Shutdown
$ docker rm -f $(docker ps -q --filter name=api.1)
$ docker service ls --format '{{.Name}} {{.Replicas}}'    # back to 3/3 after a few seconds
api 3/3
$ docker service rm api && docker swarm leave --force
$ docker network rm docker_gwbridge         # left behind by swarm mode
```

You never restarted anything yourself: you declared "three replicas of this image" and Swarm kept it true
through an update and a failure. That idea, desired state, is the core of every orchestrator, Kubernetes
included.

## Try it

- Run `docker swarm init`, create a service with three replicas and list its tasks.
- Update the service's environment and watch the tasks replaced one by one.
- Remove one replica's container with docker rm -f and watch Swarm replace it.
- Run `docker swarm leave --force` to return to plain Docker.
- Read the deploy guide of one container platform and find where you set the port and health check.
- Translate this course's compose.yaml into the Kubernetes objects listed in this lesson.

## Quiz

1. What do all the options in this lesson have in common?
   - They all need Kubernetes
   - **They all run the same OCI image; what differs is who operates the machines, scaling and restarts** (answer)
   - They all need Docker Desktop
   - Nothing
   Why: Build once, run anywhere: the image from lesson 7 runs on a VM, a PaaS, Swarm or Kubernetes unchanged.

2. What must an image do to run well on most container platforms?
   - Include SSH
   - **Listen on the port the platform gives it (often $PORT), log to stdout, keep no state on local disk and stop cleanly on SIGTERM** (answer)
   - Run as root
   - Be larger than 1GB
   Why: Platforms route traffic to the port, collect stdout, replace instances at any time and send SIGTERM before stopping them.

3. In Docker Swarm, what happens when a replica's container dies?
   - Nothing until you restart it
   - **The manager sees fewer running tasks than desired and starts a replacement** (answer)
   - The service is deleted
   - All replicas restart
   Why: Orchestrators compare desired state with actual state and correct the difference: self-healing.

4. Which Kubernetes object plays the role of a Compose service with replicas?
   - A Pod
   - **A Deployment, with a Service in front for a stable name and load balancing** (answer)
   - A Namespace
   - A ConfigMap
   Why: The Deployment keeps N pods of your image running and rolls updates; the Service gives them one DNS name, like Compose service names.

5. When is a single server with Compose a reasonable production choice?
   - Never
   - **For a small app that can tolerate the downtime of one machine, with backups and monitoring in place** (answer)
   - Only for databases
   - Always
   Why: It is simple and cheap. Its limit is that one machine is one failure; move to a platform or orchestrator when that matters.

## Resources

- [Docker Docs: Swarm mode](https://docs.docker.com/engine/swarm/) (Docker Docs)
- [Docker Docs: deploy a stack to a swarm](https://docs.docker.com/engine/swarm/stack-deploy/) (Docker Docs)
- [Kubernetes: Deployments](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) (Kubernetes)
- [Google Cloud Run: container runtime contract](https://cloud.google.com/run/docs/container-contract) (Google Cloud)
- [The Twelve-Factor App](https://12factor.net/) (12factor.net)
