To send an SMS from a Dockerized worker, run a small loop in its own Compose service, pass the API key as a Docker secret (or an env var from an .env file), add a healthcheck that watches a heartbeat file, and set restart: unless-stopped. Give each text one idempotency key so a restart never sends it twice.
We make Ready, so the worker below calls our REST API and sticks to the request shape we document: POST /v1/messages with to, body and consent_attested, plus X-API-Key and Idempotency-Key. The Compose pieces work for any HTTP SMS API.
The stack in one picture
Three services: a Redis queue, the worker that sends, and whatever app pushes jobs. Only the first two matter here.
| Service | Job | Compose setting that matters |
|---|---|---|
redis | Holds pending texts | A named volume so jobs survive docker compose down |
worker | Pops a job, calls the API | restart, healthcheck, stop_grace_period, secrets |
app (yours) | Pushes JSON jobs | depends_on with condition: service_healthy |
The Compose file
services:
redis:
image: redis:7-alpine
volumes:
- redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 3s
retries: 5
worker:
build: ./worker
restart: unless-stopped
stop_grace_period: 30s
depends_on:
redis:
condition: service_healthy
environment:
REDIS_URL: redis://redis:6379/0
READY_API_KEY_FILE: /run/secrets/ready_api_key
secrets:
- ready_api_key
healthcheck:
test: ["CMD", "python", "healthcheck.py"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
secrets:
ready_api_key:
file: ./secrets/ready_api_key.txt
volumes:
redis-data: The key lives in a file that stays out of git (add secrets/ to .gitignore). Compose mounts it read-only at /run/secrets/ready_api_key, so it never shows in docker inspect or in the image layers the way an ENV line would.
If you'd rather use an environment variable, replace the secret with env_file: .env and put READY_API_KEY=... in that file. That's simpler for local work, but the value is visible to anyone who can inspect the container. For production hosts, see our guide to secrets managers.
The worker
This is Python 3.12 with redis and requests. It reads the key from READY_API_KEY if set, otherwise from the file named in READY_API_KEY_FILE.
# worker/worker.py
import json, os, signal, time, pathlib, uuid
import redis, requests
def api_key() -> str:
if os.environ.get("READY_API_KEY"):
return os.environ["READY_API_KEY"]
return pathlib.Path(os.environ["READY_API_KEY_FILE"]).read_text().strip()
KEY = api_key()
r = redis.Redis.from_url(os.environ["REDIS_URL"], decode_responses=True)
stopping = False
signal.signal(signal.SIGTERM, lambda *_: globals().update(stopping=True))
def send(job: dict) -> requests.Response:
return requests.post(
"https://api.tryready.com/v1/messages",
headers={"X-API-Key": KEY, "Idempotency-Key": job["key"]},
json={"to": job["to"], "body": job["body"], "consent_attested": True},
timeout=15,
)
def handle(job: dict) -> str:
for attempt in range(5):
try:
res = send(job)
except requests.RequestException:
time.sleep(2 ** attempt)
continue
if res.ok:
return "done"
if res.status_code in (429, 500) or (
res.status_code == 409 and "idempotency_in_progress" in res.text
):
time.sleep(2 ** attempt)
continue
if res.status_code == 503:
job["key"] = str(uuid.uuid4()) # not sent, so a new key is safe
time.sleep(2 ** attempt)
continue
if res.status_code == 409 and "QUIET_HOURS_BLOCK" in res.text:
return "later"
return "failed"
return "failed"
# Jobs a crashed worker left behind go back on the queue first.
while (raw := r.lmove("sms:processing", "sms:queue", "RIGHT", "LEFT")):
pass
while not stopping:
pathlib.Path("/tmp/heartbeat").touch()
raw = r.blmove("sms:queue", "sms:processing", 5, "RIGHT", "LEFT")
if raw is None:
continue
outcome = handle(json.loads(raw))
r.lrem("sms:processing", 1, raw)
if outcome == "later":
r.lpush("sms:later", raw)
elif outcome == "failed":
r.lpush("sms:failed", raw) A job is JSON such as {"key": "<uuid>", "to": "+12125550199", "body": "Your order #1042 has shipped."}. The producer creates the key once, when it creates the job. Set consent_attested to true only when the recipient agreed to texts.
The reliable-queue move (BLMOVE into sms:processing) is what makes a crash safe: the job is never only in memory. On restart the worker puts leftovers back on the queue, and because the key is part of the job, a text that did go out before the crash isn't sent again. Our deterministic key guide covers how to build keys when jobs come from events.
A 409 QUIET_HOURS_BLOCK is a time rule, not a failure. The example parks it in sms:later for a job that re-queues once the window opens. See handling quiet hours.
The healthcheck
A container that's running isn't necessarily working. The loop touches /tmp/heartbeat every few seconds, because the blocking pop times out after 5. The check fails if the file is stale:
# worker/healthcheck.py
import os, sys, time
try:
age = time.time() - os.path.getmtime("/tmp/heartbeat")
except FileNotFoundError:
sys.exit(1)
sys.exit(0 if age < 90 else 1) The window is wider than one loop on purpose. A single send can retry with backoff for a while, and you don't want a slow API call to read as a dead worker.
One honest caveat: plain Compose marks the container unhealthy but doesn't restart it. The restart policy reacts to the process exiting, not to the healthcheck. Use the status for alerting, or add an autoheal sidecar, and see observability and alerting.
Restart policy and shutdown
unless-stopped brings the worker back after a crash or a host reboot, but not after you stopped it on purpose. stop_grace_period: 30s gives the loop time to finish the current job after SIGTERM. Run the command as the container's main process (CMD ["python", "-u", "worker.py"]), or the signal never reaches Python.
FAQ
Should I use Docker secrets or an env file?
Use a secret file for anything shared or deployed, and an env file for local development. Both feed the same code above.
Can I run more than one worker?
Yes. BLMOVE hands each job to exactly one worker. Mind your account's send rate when you scale, per our rate limits guide.
Why not send from the web container?
A deploy or restart of the web app would interrupt sends, and a slow carrier would hold a request open. A worker keeps both out of the user's way.
The short version
One service, one secret file, a heartbeat check and one key per job. The messages API docs list every field, and you can create an account to get a key.