A texting worker is a small job that reads a message off a queue and calls an API. That's a good fit for a container, and it's also a good way to leak a key. An image that bakes in a credential, a compose file committed with a real value in it, a docker inspect that prints it to anyone with shell access: each of these has happened to someone.
This post builds a small worker with Docker Compose, using Ready's REST API and the request shape we document. It covers how the key gets in, how the worker retries without double-texting, and how you tell the container is healthy. It assumes Docker with Compose v2 and Node 20 or later for the built-in fetch. The pattern works with any provider that accepts an idempotency key.
What you need before you start
- An API key. Ready authenticates with an
X-API-Keyheader. Create a test key first so you can try everything without sending live texts. Our sandbox and test numbers guide covers what a test key does. - A card and a number to send live. A card on file and a number of your own are required, and the number is $2 a month. Each segment is $0.0075 plus a $0.0045 carrier fee.
- Consent. Every send sets
consent_attested, your promise the recipient agreed to texts. Only set it where your own records back it.
The layout
sms-worker/
Dockerfile
compose.yaml
worker.js
.env # never committed
.dockerignore The queue here is a Redis list, because it keeps the example short. If you want retries, rate limits and a dashboard, see sending from a BullMQ worker, which uses the same API call.
The Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY worker.js ./
USER node
CMD ["node", "worker.js"] Notice what isn't here: no ENV READY_API_KEY, no ARG that takes the key at build time. Anything set with ENV or ARG can be read back from the image history. The image holds code; the running container holds the secret.
Add a .dockerignore with .env, .git and node_modules, so a build context never carries the key into a layer.
The compose file
services:
redis:
image: redis:7-alpine
restart: unless-stopped
worker:
build: .
restart: unless-stopped
depends_on:
- redis
environment:
REDIS_URL: redis://redis:6379
READY_API_KEY: ${READY_API_KEY:?set READY_API_KEY in .env}
healthcheck:
test: ["CMD", "node", "-e", "process.exit(Date.now() - require('fs').statSync('/tmp/alive').mtimeMs < 60000 ? 0 : 1)"]
interval: 30s
timeout: 5s
retries: 3 Compose reads READY_API_KEY from your shell or from a .env file next to the compose file. The :? form makes docker compose up stop with a message if the variable is empty, which beats a worker that boots and fails every send with a 401.
Keep .env out of Git with a .gitignore entry, and run a secret scanner before commits. Most leaks aren't attacks. They're a file pushed by mistake.
An env var, or a secret file?
An environment variable is the simplest route and fine for a laptop or a single host you control. It has a cost: the value shows in docker inspect and in the process environment of the container. For anything shared, mount the key as a file.
| Option | Visible in docker inspect | Good for |
|---|---|---|
environment: from .env | Yes | Local work, one trusted host |
Compose secrets: file | No | A single host with several people |
| Your orchestrator's secret store | No | Production on a cluster |
With Compose, a file secret looks like this:
services:
worker:
secrets:
- ready_api_key
secrets:
ready_api_key:
file: ./secrets/ready_api_key.txt The container then finds the key at /run/secrets/ready_api_key, and the worker reads that path when the env var is absent. In production, fetch the key from a secrets manager at deploy time, as shown in storing your SMS API key in AWS Secrets Manager or Vault.
The worker
The worker uses ES module imports, so set "type": "module" in package.json and add ioredis as a dependency. The loop touches a file on every pass, and the health check in the compose file fails if that file goes stale for a minute, which catches a worker that's hung rather than crashed.
import { readFileSync, writeFileSync } from 'node:fs';
import Redis from 'ioredis';
const key = process.env.READY_API_KEY
?? readFileSync('/run/secrets/ready_api_key', 'utf8').trim();
const redis = new Redis(process.env.REDIS_URL);
async function send(job) {
const res = await fetch('https://api.tryready.com/v1/messages', {
method: 'POST',
headers: {
'X-API-Key': key,
'Idempotency-Key': job.id,
'Content-Type': 'application/json',
},
body: JSON.stringify({ to: job.to, body: job.body, consent_attested: true }),
signal: AbortSignal.timeout(20000),
});
return res.status;
}
while (true) {
writeFileSync('/tmp/alive', String(Date.now()));
const item = await redis.blpop('sms:outbox', 5);
if (!item) continue;
const job = JSON.parse(item[1]);
try {
const status = await send(job);
if (status === 429 || status >= 500) {
await redis.rpush('sms:outbox', item[1]);
await new Promise((r) => setTimeout(r, 5000));
}
} catch {
await redis.rpush('sms:outbox', item[1]);
await new Promise((r) => setTimeout(r, 5000));
}
} Drop a job on the queue with docker compose exec redis redis-cli rpush sms:outbox '{"id":"3f1c2a8e-7b3d-4e9a-9c61-2d0f8b4a1e77","to":"+12125550199","body":"Your order #1042 has shipped."}'.
This is a sketch, not a finished service. It retries forever and it doesn't separate a bad request from a flaky one. A 4xx other than 429 will fail the same way every time, so a real worker gives up on it and records the failure. The status-code table in the BullMQ post shows how to split them.
Why the idempotency key matters in a container
Containers get restarted: a deploy, a crash, an out-of-memory kill, a host reboot. If the worker dies after the API accepted a text and before it recorded success, the job goes back on the queue and runs again. Without a key, the recipient gets two texts and you pay for two.
Use an id that's made once per message, at the moment you create the job, and reused on every retry. That's why the job above carries its own id rather than letting the worker invent one. Ready keeps the key for 7 days, and a retry with the same key returns the first answer. The mechanics are in idempotency and duplicate texts and deterministic idempotency keys.
Operating it
A few habits keep a container worker boring.
- Pin the base image. Use a version tag, and rebuild on a schedule for security patches.
- Handle shutdown. Compose sends SIGTERM on
docker compose stop. Finish the in-flight request, don't pop another job, then exit. Otherwise a stop mid-request leaves you guessing whether a text went out. - Log without the key. Log the job id, the status and the time. Never log request headers.
- Watch the count. A sudden jump in sends per hour is the first sign of a runaway loop or a leaked key. Observability for SMS APIs lists the alerts worth setting.
- Rotate with overlap. Put the new key in, restart the worker, confirm sends succeed, then revoke the old one. The rotation playbook has the order.
Where to go from here
You now have a worker that takes the key from its environment or a secret file, restarts on failure and doesn't double-send. The next steps are the ones any queue consumer needs: a retry cap, a dead-letter list and a rate limit that matches your registration. Quiet hours also apply to API texts, so a send outside the window can come back refused; the error codes docs list the answers.
When you're ready to try it, sign up, make a test key and run docker compose up.
Accounts opened before November 12, 2026 keep their signup prices, shown under Billing.