Chapter 4 · Lesson 15 of 18
Deploy and operate

What a worker and a cron job are (service types explained)

A web service answers requests on a port, a worker runs continuously without one, and a cron job starts on a schedule, does its work and exits.

By the end you will

Classify each part of an app as web, private, worker or cron and run it as a container with the right restart behavior.

Time
12 min
Level
Beginner
Check
4 questions
You need
  • Basic Docker and Compose knowledge
  • A server where you can run containers

Hosting platforms usually sort apps into four service types: web services, private services, background workers and cron jobs. The difference is how the process starts, whether it listens on a port and who may connect to it. On your own server these map directly to containers: a web service publishes a port through a proxy, a private service sits on an internal network, a worker is a long-running container with no port, and a cron job is a container that runs and exits.

How it works#

Think of any app as a few processes built from the same code. One answers HTTP. Another sends emails. A third cleans old records every night. Each has a different lifetime and a different network exposure. Naming them helps you decide which need a restart policy, which need a public address and which should never be reachable from outside.

The four service types#

Web service. It listens on a port and answers requests from browsers or API clients. It is public, normally behind a reverse proxy that terminates HTTPS. It runs continuously and should have a health check.

Private service. It also listens on a port, but only other services connect to it. Typical examples are a database, a cache or an internal API. It is not reachable from the internet. See private networking between services.

Background worker. It runs continuously but has no port. It pulls tasks from a queue, polls a table or processes a stream. If it crashes it should restart. You scale it by running more copies.

Cron job. It runs on a schedule, does its work and exits. It holds no state in the process and has no port. If one run fails, the next scheduled run starts fresh.

A queue example#

A signup form sends a welcome email. If the web service sends it inline, the user waits for the mail server and a failure breaks signup. Instead the web service pushes a job onto a queue (Redis, a database table or a message broker) and returns at once. A worker reads jobs and sends the emails. If the mail provider is down, the job stays in the queue and the worker retries later.

yaml
services:
  web:
    image: myapp:1.4.0
    command: ["serve"]
    ports:
      - "127.0.0.1:8080:8080"
    depends_on:
      - redis
  worker:
    image: myapp:1.4.0
    command: ["work"]
    restart: unless-stopped
    depends_on:
      - redis
  redis:
    image: redis:7
    restart: unless-stopped

Web and worker use the same image with different commands. Only web publishes a port, and only on loopback. Redis publishes nothing, since the others reach it on the Compose network. A restart policy on the worker brings it back after a crash or reboot, as covered in Docker restart policies.

Running a cron job on your own server#

A scheduled job is a container that starts, runs a command and exits. Define it as a Compose service you do not start by default, then call it from the host scheduler.

yaml
services:
  nightly-report:
    image: myapp:1.4.0
    command: ["report", "--since", "yesterday"]
    profiles: ["jobs"]

The profiles key keeps the service out of a normal docker compose up. Run it once by hand to test:

bash
docker compose run --rm nightly-report

Then schedule it. With cron, edit the deploy user’s crontab with crontab -e and add a line such as:

output
15 2 * * * cd /srv/myapp && docker compose run --rm nightly-report >> /var/log/nightly-report.log 2>&1

This runs at 02:15 server time every day. Cron has a minimal environment, so use absolute paths and cd into the project, as shown. Make sure /var/log/nightly-report.log is writable by that user.

A systemd timer is the alternative. You write a .service unit that runs the same command with Type=oneshot, and a .timer unit with an OnCalendar= schedule. Timers log to the journal, can catch up after downtime when Persistent=true is set, and are covered with services in run a service with systemd.

Cron jobs must be safe to run twice, since a slow run can overlap the next one. A lock, such as flock around the command, or a database-level lock stops overlap.

Check it worked#

Confirm each type behaves as intended:

bash
docker compose ps
docker compose logs --tail 20 worker
docker compose run --rm nightly-report; echo "exit code: $?"

ps should show web, worker and redis running, with only web listing a published port. The worker’s logs should show it waiting for or processing jobs. The one-off job should print its output and return exit code 0, and docker ps -a should not show it lingering because of --rm. After the first scheduled time, check the log file or journalctl for the run.

Edge cases and gotchas#

  • One image, many commands: Reuse the same image for web, worker and jobs to keep versions in step. Override the command per service.
  • Overlapping runs: If a job takes longer than its interval, two copies can run. Use a lock or lengthen the interval.
  • Time zones: Cron uses the server’s time zone. Containers often run in UTC. State the zone you expect in schedules and logs.
  • Silent failures: A cron job that fails writes to a log nobody reads. Alert on a missing success signal, as in monitor uptime simply.
  • Workers and deploys: On redeploy, give a worker time to finish its current task before stopping, for example with a stop grace period, or tasks may be cut off and retried.
  • Not every worker needs a queue: A loop that polls an API every minute is a worker too, but a cron job may be simpler.

Troubleshooting#

SymptomLikely causeFix
Worker exits right after startingCommand finishes, or a config errorRead docker compose logs worker and fix the command or env
Cron job never runsWrong crontab, path or userCheck crontab -l, use absolute paths, look at syslog or the log file
Job works by hand, fails in cronMinimal cron environmentUse full paths and cd into the project directory
Queue grows without boundWorker down or too slowCheck worker logs, restart it, add more worker copies
Two copies of a job run togetherRun time exceeds intervalAdd flock or a database lock

Quick reference#

TypePortLifetimeContainer pattern
Web serviceYes, public via proxyLong-runningports on loopback plus proxy
Private serviceYes, internal onlyLong-runningNo ports, shared network
WorkerNoLong-runningrestart: unless-stopped
Cron jobNoRuns then exitscompose run —rm from cron or a timer

Next#

Continue with private networking between services.

Check what you learned4 questions
1What most clearly separates a background worker from a web service?
2How does a cron job differ from a worker in terms of process lifetime?
3Which restart policy suits a worker container?
4Which tools can trigger a scheduled container on your own server?

Frequently asked questions

What is a background worker?

A background worker is a long-running process that does work without serving web requests, usually by taking jobs from a queue such as emails to send or images to resize.

What is the difference between a cron job and a worker?

A cron job runs at set times and then exits. A worker keeps running and reacts to jobs as they arrive.

How do I run a cron job with Docker?

Use the host's cron or a systemd timer to run docker compose run --rm with the job's service. Each run starts a fresh container that exits when the task is done.

What is a private service?

A private service is reachable by your other services over an internal network but not from the public internet, such as a database or an internal API.

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios