Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 111 ยท Registries and CI/CD

Deploying on a Single Host

Run Docker Compose in production on one server: restart policies, health checks, a reverse proxy, TLS, resource limits, log rotation, updates and rollbacks.

Not every application needs a cluster. A single virtual machine with Docker and Compose can serve a surprising amount of traffic, costs a few dollars a month, and has almost nothing to learn beyond what you already know. For side projects, internal tools, small businesses and many real products, one well-run host is the right answer, and it is also the best way to understand what bigger platforms automate for you.

In this lesson you will take a Compose file from "works on my laptop" to "fit to run on a server": restart policies, health checks, a reverse proxy in front of the app, limits, log rotation, a safe update procedure and a rollback. The Compose file and the update test below were run for real, using a small Node.js app image and Nginx. Anything that needs a public domain name, a real firewall or certificates is shown as a read-only example, because it cannot run on the machine used to write this lesson.

The target architecture

TEXT
 Internet
    |
    | 80 / 443
    v
 +--------+   private Docker network   +-------------+
 | proxy  | -------------------------> |    app      |
 | (nginx |   http://app:3000          | (no public  |
 |  or    |                            |  port)      |
 | Caddy) |                            +------+------+
 +--------+                                   |
                                         named volume
                                        (database etc.)

Only the proxy publishes ports to the outside world. The application containers have no ports: entry at all; they are reachable only through the Compose network, by service name. That single decision removes a whole class of exposure mistakes (see Publishing Ports).

A production-minded Compose file

This is the complete compose.yaml that was tested. The image tcd-b12-node:1 is built from the Node.js recipe lesson; in your project it would be something like ghcr.io/your-org/app:3f9a2c1.

YAML
name: shop

services:
  app:
    image: ${APP_IMAGE:-registry.example.com/shop/app:3f9a2c1}
    restart: unless-stopped
    environment:
      PORT: "3000"
    healthcheck:
      test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:3000/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
      interval: 5s
      timeout: 3s
      retries: 3
      start_period: 5s
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: 256M
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

  proxy:
    image: nginx:alpine
    restart: unless-stopped
    depends_on:
      app:
        condition: service_healthy
    ports:
      - "127.0.0.1:18105:80"
    volumes:
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

(In the test the image was a local one, so the file also set pull_policy: never; on a real server you pull from your registry.) The proxy binds to 127.0.0.1:18105 only so the test did not expose anything on the lab machine; on a real server you would publish "80:80" and "443:443". The Nginx configuration it mounts:

NGINX
upstream app {
    server app:3000;
}

server {
    listen 80;
    server_name _;

    location / {
        proxy_pass http://app;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Start it and wait until everything is healthy:

CONSOLE
$ docker compose config -q && echo valid
valid
$ docker compose up -d --wait
 Container shop-proxy-1 Creating
 Container shop-proxy-1 Created
 Container shop-app-1 Starting
 Container shop-app-1 Started
 Container shop-app-1 Waiting
 Container shop-app-1 Healthy
 Container shop-proxy-1 Starting
 Container shop-proxy-1 Started
$ docker compose ps
NAME         IMAGE            COMMAND                  SERVICE   CREATED          STATUS                   PORTS
shop-app-1   tcd-b12-node:1   "docker-entrypoint.sโ€ฆ"   app       11 seconds ago   Up 9 seconds (healthy)   3000/tcp
shop-proxy-1 nginx:alpine     "/docker-entrypoint.โ€ฆ"   proxy     10 seconds ago   Up 2 seconds             127.0.0.1:18105->80/tcp
$ curl -s localhost:18105/
{"message":"Hello from a container","env":"production"}

(The test project was named differently, so container names in your own output follow your name: value.) Note the order in the log: the proxy is created first but starts only after app is Healthy, because of depends_on with condition: service_healthy. --wait makes the command return only when every service is running and healthy, which is exactly what a deploy script wants. More on this in Startup Order and Health.

docker compose config -q validates the file and resolves variables without printing anything. Run it in CI so a typo never reaches the server.

Restart policies: surviving crashes and reboots

restart: unless-stopped tells Docker to bring the container back after crashes, after a daemon restart and after a server reboot, unless you stopped it. For the reboot case the Docker service itself must start at boot, which is the default with the official Linux packages (systemctl enable docker).

The behavior has one subtlety that surprises people. Here is a real test. First, make the app's main process exit, as a crash would, and look at the restart counter:

CONSOLE
$ docker exec shop-app-1 sh -c 'kill 1'
$ sleep 6; docker compose ps --format 'table {{.Service}}\t{{.Status}}'
SERVICE   STATUS
app       Up 6 seconds (healthy)
proxy     Up 17 seconds
$ docker inspect -f 'restarts={{.RestartCount}} policy={{.HostConfig.RestartPolicy.Name}}' shop-app-1
restarts=1 policy=unless-stopped

The process exited (here cleanly, after receiving SIGTERM from kill 1), and unless-stopped restarted the container anyway, even with exit code 0. The proxy never noticed. Now stop it through Docker, with docker kill:

CONSOLE
$ docker kill shop-app-1
$ sleep 4; docker inspect -f 'restarts={{.RestartCount}} running={{.State.Running}}' shop-app-1
restarts=1 running=false

It stays down. A stop that you request through Docker (docker stop, docker kill) counts as intentional, so the policy leaves it alone, even after a reboot, until you run docker compose up -d or docker start again. That is what you want in practice: you can stop a service for maintenance without a restart loop fighting you.

Policy After a crash After a reboot After you stop it
no (default) stays down stays down stays down
on-failure[:N] restarts on non-zero exit (max N times) stays down stays down
always restarts restarts restarts on daemon restart
unless-stopped restarts restarts stays down

For servers, unless-stopped is the usual choice. A container that crashes in a tight loop is restarted with growing delays, so look at docker compose logs when the restart count climbs.

Limits and log rotation

Two settings protect a single host from one misbehaving container taking everything down. The first is resource limits. In the test, Docker applied them as expected:

CONSOLE
$ docker inspect -f '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}' shop-app-1
268435456 500000000

That is 256 MiB of memory and half a CPU. Without a memory limit, a leak in one service can make the kernel kill something else, perhaps your database (see Resource Limits). The deploy.resources.limits section works with plain docker compose up, not only in Swarm.

The second is log rotation. The default json-file driver keeps every line of output forever, and a chatty app will eventually fill the disk. The options max-size: "10m" and max-file: "3" keep at most about 30 MB per container:

CONSOLE
$ docker inspect -f '{{json .HostConfig.LogConfig}}' shop-app-1
{"Config":{"max-file":"3","max-size":"10m"},"Type":"json-file"}

You can set the same defaults for every container in /etc/docker/daemon.json instead of repeating them in each file. See Logging and Monitoring.

Updating without a hero weekend

The update procedure is only three commands, and it is the same on the first deploy and the hundredth:

CONSOLE
$ APP_IMAGE=registry.example.com/shop/app:a81c0de docker compose pull app
$ APP_IMAGE=registry.example.com/shop/app:a81c0de docker compose up -d --wait
$ docker compose ps

Compose compares the new configuration with the running containers, recreates only the services that changed (here app, not proxy) and, with --wait, returns when they are healthy. To see what it costs, the test hit the site four times a second while updating to a new image:

CONSOLE
$ for i in $(seq 1 120); do curl -s -o /dev/null -w '%{http_code}\n' --max-time 2 localhost:18105/; sleep 0.25; done > codes.txt &
$ APP_IMAGE=tcd-b12-node:2 docker compose up -d --wait
$ wait; sort codes.txt | uniq -c
    117 200
      3 502

117 requests succeeded and 3 returned 502 Bad Gateway: the short gap while the old container was removed and the new one started. For many sites that is acceptable. If it is not, you have options:

  • Run two copies of the app (docker compose up -d --scale app=2), so the proxy has another backend while one restarts, and let the proxy retry on a failed upstream. Nginx resolves the name app when it starts, so reload it (docker compose exec proxy nginx -s reload) after the replicas change.
  • Start the new version beside the old one (a "blue/green" pair of services), switch the proxy to it, then remove the old one.
  • Use an orchestrator that does rolling updates for you; see Why Orchestration?.

Database migrations are the real zero-downtime problem. If the new code needs a changed schema, make the migration backward compatible (add columns first, remove old ones in a later release) so the old and new versions can run at the same time.

Rolling back

Because every release has its own tag, a rollback is the update command with the previous tag:

CONSOLE
$ APP_IMAGE=registry.example.com/shop/app:3f9a2c1 docker compose up -d --wait

This only works if you never deploy latest and never delete old tags. See Tagging and Versioning Strategies. Keep the tag you deploy in a file or a CI variable so you always know what is running. docker compose images or docker inspect tells you the truth if you are not sure.

TLS with a reverse proxy (read-only example)

In production you want HTTPS, and the proxy is the place to do it. Caddy gets and renews certificates from Let's Encrypt by itself, which makes it the shortest path. This is a read-only example: it needs a real domain pointing at your server and open ports 80 and 443.

YAML
services:
  proxy:
    image: caddy:2
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
    depends_on:
      app:
        condition: service_healthy

volumes:
  caddy_data:
TEXT
shop.example.com {
    reverse_proxy app:3000
}

The caddy_data volume stores the certificates, so they survive container recreation (without it you would request new ones on each deploy and hit rate limits). With Nginx you would use Certbot or a companion container instead. Proxies are covered in more depth in Nginx and Reverse Proxies.

The host itself

Containers are only half of a deployment. A short list for the server:

  • Firewall: allow only SSH, 80 and 443. Docker writes its own iptables rules for published ports, which can bypass tools like ufw; publish internal services on 127.0.0.1 or not at all. See DNS, Proxies and Firewalls.
  • Secrets: keep them in files with restricted permissions or in Compose secrets, never in the image or in Git (Managing Secrets).
  • Data: put databases and uploads in named volumes and schedule backups. A volume is not a backup.
  • Cleanup: old images pile up after many deploys; schedule a safe prune (Cleaning Up).
  • Monitoring: at least an uptime check from outside and an alert when disk usage is high.
  • Updates: patch the host OS and Docker, and rebuild images regularly to pick up base-image fixes.

When a single host is enough (and when it is not)

Choose a single host when downtime during a deploy or a rare reboot is acceptable, your traffic fits one machine, and you value simplicity. Move on when you need several servers for capacity or availability, automatic rescheduling when a machine dies, or rolling updates without any error. Choosing Your Deployment Path compares the options.

To clean up the test: docker compose down stops and removes the containers and the network, and leaves named volumes in place unless you add -v.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which services in a typical single-host Compose deployment should publish ports to the internet?

    The proxy is the single public entry point. Other services are reachable by service name on the Compose network, which removes accidental exposure of apps and databases.
  2. 2. You run docker kill on a container with restart: unless-stopped. What happens?

    In the test the restart counter stayed at 1 and the container remained down. unless-stopped restarts after crashes and reboots but respects a manual stop.
  3. 3. Why set max-size and max-file on the json-file logging driver?

    By default json-file never rotates. With max-size: 10m and max-file: 3 at most about 30 MB per container is kept.
  4. 4. What does docker compose up -d --wait add compared to docker compose up -d?

    --wait makes the command block until services are running (and healthy, if they have a healthcheck). A deploy script can then fail fast instead of assuming success.
  5. 5. How do you roll back a bad release in this setup?

    Each release has its own immutable tag, so rolling back means deploying the earlier tag. This is why you never deploy latest and never delete old tags too early.

Summary

  • One host with Compose is a legitimate production setup for many projects. Only the reverse proxy publishes ports; apps and databases live on the private network.
  • Use restart: unless-stopped, health checks and depends_on: condition: service_healthy; docker compose up -d --wait returns when everything is healthy.
  • A crash restarts the container, but a stop through Docker (docker stop, docker kill) is respected and leaves it down.
  • Protect the host with deploy.resources.limits and log rotation (max-size, max-file).
  • Update with docker compose pull and docker compose up -d --wait; only changed services are recreated. A plain recreate caused a brief gap (3 of 120 requests returned 502 in the test); use replicas, blue/green or an orchestrator if that is too much.
  • Deploy immutable tags, never latest, so a rollback is one command.
  • TLS belongs on the proxy (Caddy automates certificates, read-only example); back up volumes, rotate secrets and keep the host and images patched.

Next: Containerizing a Node.js App