← Blog

·

Running the WhatsApp webhook in production with Docker on a VPS

Updated on November 10, 2026

To run the WhatsApp webhook with Docker on a VPS you need four pieces: a reverse proxy that serves HTTPS with a valid certificate (Caddy, or Nginx with Certbot), an app that returns 200 fast and pushes the event onto a queue, a worker that processes the queue, and Redis to store the jobs. Add restart: unless-stopped, a HEALTHCHECK and log rotation, and the stack recovers from crashes on its own without filling the disk.

This article includes the complete files (docker-compose.yml, Dockerfile, Caddyfile and a Node.js app) and explains each decision. If your webhook isn’t receiving anything yet, start with the WhatsApp webhook not working checklist. If you’d rather not maintain a server, compare with a serverless webhook.

What Meta requires from the endpoint

Requirements first, infrastructure second. According to Create a webhook endpoint and the webhooks overview:

RequirementWhat the docs sayImpact on Docker
HTTPSValid TLS certificate; self-signed is not supportedThe proxy must issue and renew a public certificate
VerificationGET with hub.mode=subscribe, hub.challenge and hub.verify_token; respond 200 with the hub.challengeGET route in the app, token in an environment variable
SignaturePOST with X-Hub-Signature-256, HMAC-SHA256 of the body keyed with the app secret, sha256= prefixThe proxy must not alter the body; validate against the raw bytes
Response200 for a valid requestRespond before processing
RedeliveryFailures are retried immediately, then with decreasing frequency for up to 7 daysDuplicates happen; the worker must be idempotent
SizePayloads up to 3 MBRaise the body limit in the proxy and the app
BatchingUp to 1,000 updates per POST, with no batching guaranteeIterate over entry[] and changes[]

Meta doesn’t publish a maximum response time, but anything other than 200 triggers a redelivery. That’s why the design is always the same: validate, enqueue, respond. Signature validation is covered in depth in how to validate X-Hub-Signature-256.

The architecture on the VPS

Internet (Meta or Vectalk)
  -> :443 caddy  (HTTPS, automatic certificate)
       -> app:3000   (verifies, validates, enqueues, returns 200)
            -> redis:6379  (BullMQ queue, AOF persistence)
                 -> worker  (processes, deduplicates, runs your logic)

Only Caddy publishes ports. The app, the worker and Redis stay on the internal Compose network. This matters because, according to Docker’s firewall documentation, ports published with ports: go through Docker’s own rules and can bypass whatever you configured in ufw. If port 3000 isn’t published, there’s nothing to leak.

Folder layout:

webhook/
  docker-compose.yml
  .env
  conf/
    Caddyfile
  app/
    Dockerfile
    package.json
    server.js
    worker.js

Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →

The app: verification, signature and queue

The receiver uses Express and BullMQ. The critical part is reading the body as a Buffer (express.raw) before any parsing, because the HMAC is computed over the exact bytes Meta sent.

app/package.json:

{
  "name": "whatsapp-webhook",
  "type": "module",
  "private": true,
  "dependencies": {
    "bullmq": "^5.0.0",
    "express": "^4.21.0",
    "ioredis": "^5.4.0"
  }
}

app/server.js:

import express from "express";
import crypto from "node:crypto";
import { Queue } from "bullmq";

const {
  PORT = "3000",
  VERIFY_TOKEN,
  APP_SECRET,          // required if Meta calls you directly
  PATH_SECRET,         // secret in the URL, useful when there is no signature
  REDIS_HOST = "redis",
} = process.env;

const connection = { host: REDIS_HOST, port: 6379 };
const queue = new Queue("whatsapp-webhook", { connection });
const app = express();
const WEBHOOK_PATH = PATH_SECRET ? `/webhook/${PATH_SECRET}` : "/webhook";

function validSignature(raw, header = "") {
  const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(raw).digest("hex");
  const a = Buffer.from(header);
  const b = Buffer.from(expected);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// Verification (GET) sent by Meta when you save the URL
app.get(WEBHOOK_PATH, (req, res) => {
  if (req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN) {
    return res.status(200).type("text/plain").send(req.query["hub.challenge"]);
  }
  return res.sendStatus(403);
});

// Events (POST): validate, enqueue, respond
app.post(WEBHOOK_PATH, express.raw({ type: "*/*", limit: "4mb" }), async (req, res) => {
  if (APP_SECRET && !validSignature(req.body, req.get("x-hub-signature-256"))) {
    console.warn(JSON.stringify({ evt: "invalid_signature", ip: req.ip }));
    return res.sendStatus(401);
  }
  const jobId = crypto.createHash("sha256").update(req.body).digest("hex");
  try {
    await queue.add("event", { raw: req.body.toString("utf8") }, {
      jobId,                       // an identical POST redelivered won't duplicate the job
      attempts: 5,
      backoff: { type: "exponential", delay: 2000 },
      removeOnComplete: 1000,
      removeOnFail: 5000,
    });
  } catch (err) {
    console.error(JSON.stringify({ evt: "queue_unavailable", error: err.message }));
    return res.sendStatus(503);   // no queue: ask for redelivery instead of losing the event
  }
  console.log(JSON.stringify({ evt: "enqueued", jobId, bytes: req.body.length }));
  return res.sendStatus(200);
});

// Healthcheck: the process is up and can reach Redis
app.get("/health", async (_req, res) => {
  try {
    const redis = await queue.client;
    await redis.ping();
    res.status(200).json({ ok: true });
  } catch {
    res.status(503).json({ ok: false });
  }
});

const server = app.listen(Number(PORT), () => console.log(JSON.stringify({ evt: "ready", port: PORT })));

// docker stop sends SIGTERM: finish in-flight requests and close the queue
process.on("SIGTERM", () => {
  server.close(async () => {
    await queue.close();
    process.exit(0);
  });
});

Three details in this code:

  • Returning 503 when Redis is down is intentional. If you return 200 without having stored the event, it’s lost. With 503, Meta redelivers.
  • The jobId is a hash of the body. BullMQ ignores a job whose ID already exists in the queue, so an identical redelivered POST doesn’t create duplicate work. That doesn’t replace deduplication in the worker: a redelivery can arrive after the old job has been removed.
  • limit: "4mb" covers the payloads of up to 3 MB that Meta documents. The express.raw default is much smaller.

The worker: process and deduplicate

The worker runs from the same image with a different command. It walks the batch, skips events already processed and only marks an event as processed after it finishes.

app/worker.js:

import { Worker } from "bullmq";
import Redis from "ioredis";

const connection = { host: process.env.REDIS_HOST || "redis", port: 6379 };
const redis = new Redis(connection);
const TTL = 8 * 24 * 3600; // longer than the 7-day redelivery window

async function once(key, fn) {
  if (await redis.exists(key)) return;
  await fn();
  await redis.set(key, "1", "EX", TTL);
}

async function handleMessage(msg, metadata) {
  // your logic: save to the database, call the CRM, reply through the API...
  console.log(JSON.stringify({ evt: "message", wamid: msg.id, type: msg.type, phone_number_id: metadata?.phone_number_id }));
}

async function handleStatus(st) {
  console.log(JSON.stringify({ evt: "status", wamid: st.id, status: st.status }));
}

const worker = new Worker("whatsapp-webhook", async (job) => {
  const payload = JSON.parse(job.data.raw);
  for (const entry of payload.entry ?? []) {
    for (const change of entry.changes ?? []) {
      const v = change.value ?? {};
      for (const msg of v.messages ?? []) {
        await once(`seen:msg:${msg.id}`, () => handleMessage(msg, v.metadata));
      }
      for (const st of v.statuses ?? []) {
        await once(`seen:st:${st.id}:${st.status}`, () => handleStatus(st));
      }
    }
  }
}, { connection, concurrency: 10 });

worker.on("failed", (job, err) => console.error(JSON.stringify({ evt: "job_failed", id: job?.id, error: err.message })));

process.on("SIGTERM", async () => {
  await worker.close(); // waits for running jobs
  await redis.quit();
  process.exit(0);
});

The status key includes the status itself (sent, delivered, read, failed) because each one is a separate event for the same wamid. For the full design of queues, retries and idempotency, see WhatsApp API integration architecture. If you’ll also send messages from the same infrastructure, the send queue with Redis and BullMQ shows how to throttle by throughput.

Dockerfile with HEALTHCHECK

app/Dockerfile:

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev
COPY . .
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -qO- http://127.0.0.1:3000/health || exit 1
CMD ["node", "server.js"]

Per the Dockerfile reference, the healthcheck command returns 0 for healthy and 1 for unhealthy, and the container only becomes unhealthy after --retries consecutive failures (default 3). The defaults for --interval and --timeout are 30 seconds; here the timeout drops to 5 seconds, because a /health that takes 30 seconds is already a problem. --start-period gives the process time to boot without counting failures.

The exec-form CMD (["node", "server.js"]) lets Node receive SIGTERM directly, with no shell in between swallowing the signal. wget already ships with the Alpine image.

docker-compose.yml: restarts, dependencies and logs

x-logging: &logging
  driver: json-file
  options:
    max-size: "10m"
    max-file: "5"

services:
  caddy:
    image: caddy:2
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
      - "443:443/udp"
    volumes:
      - ./conf:/etc/caddy
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      app:
        condition: service_healthy
    logging: *logging

  app:
    build: ./app
    env_file: .env
    restart: unless-stopped
    init: true
    depends_on:
      redis:
        condition: service_healthy
    logging: *logging

  worker:
    build: ./app
    command: ["node", "worker.js"]
    env_file: .env
    restart: unless-stopped
    init: true
    healthcheck:
      disable: true
    depends_on:
      redis:
        condition: service_healthy
    logging: *logging

  redis:
    image: redis:7-alpine
    command: ["redis-server", "--appendonly", "yes"]
    restart: unless-stopped
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 3s
      retries: 5
    logging: *logging

volumes:
  caddy_data:
  caddy_config:
  redis_data:

And the .env file (kept out of Git):

VERIFY_TOKEN=a-long-random-token
APP_SECRET=your-meta-app-secret
PATH_SECRET=
REDIS_HOST=redis

Restart policy

The restart policies documentation defines four options:

PolicyBehaviorWhen to use
noNever restarts (default)Never in production
on-failureRestarts if the process exits with a non-zero code; doesn’t come back after the daemon restartsJobs that can finish successfully
alwaysAlways restarts; if you stopped it manually, it comes back when the daemon restartsWhen the service must come up even after a manual stop and a reboot
unless-stoppedLike always, but a manually stopped container stays stopped after the daemon restartsA sensible default for a webhook

Two points in the docs catch people off guard. First, the policy only takes effect after the container has stayed up for at least 10 seconds; the rule exists so that a container that never really starts doesn’t fall into a restart loop. If the app crashes right at startup, check the logs instead of counting on the policy. Second, restart policies react to the container exiting: the docs don’t list the unhealthy status as a restart trigger. In Compose without Swarm, the healthcheck feeds depends_on and lets you see the problem in docker compose ps. If you want a restart when the app hangs, make the process exit with an error in that situation (for example, process.exit(1) on a fatal error) and let the policy bring it back.

For containers to come back after a VPS reboot, the Docker daemon itself must start on boot (sudo systemctl enable docker on systemd distributions).

depends_on with condition

With condition: service_healthy, Compose waits for the dependency’s healthcheck to pass before starting the service. In the order above, Redis becomes healthy, then the app, and only then does Caddy start forwarding traffic. The worker inherits the image’s HEALTHCHECK, which would probe an HTTP port it never opens, hence disable: true.

Log rotation

The default json-file driver doesn’t rotate: per the driver documentation, max-size is unlimited by default and max-file only works when max-size is set. A busy webhook will quietly fill the disk of a small VPS. The x-logging block applies 10 MB per file and 5 files per container. If you’d rather set it for every container in /etc/docker/daemon.json, remember the values are strings ("max-file": "5") and the change only applies to containers created afterwards.

To read them:

docker compose logs -f --since 10m app worker
docker compose logs caddy | grep -i error

The app writes one JSON line per event with the wamid, status and size, not the whole payload. WhatsApp messages contain personal data (name, phone number, content), and keeping all of it in container logs with no access control or retention period makes compliance harder under privacy laws such as Brazil’s LGPD (Law 13,709/2018) or the GDPR. Check with your legal team; this article is not legal advice.

HTTPS with Caddy

conf/Caddyfile:

webhook.yourcompany.com {
    handle /health {
        respond 404
    }
    handle {
        reverse_proxy app:3000
    }
}

That’s it. According to the automatic HTTPS docs, Caddy issues and renews the certificate on its own through a public CA (Let’s Encrypt, with ZeroSSL as fallback) when three conditions hold: the domain’s A/AAAA record points to the VPS, ports 80 and 443 are open to the internet, and the data directory is writable and persistent. It also redirects HTTP to HTTPS.

The data directory is the reason for the caddy_data:/data volume. The official image page warns that certificates and keys live there; without a volume, every container recreation requests a new certificate and you may hit the CA’s issuance limits. The same page recommends mounting the /etc/caddy folder rather than the Caddyfile alone, as in the Compose file above. To apply Caddyfile changes without taking the container down:

docker compose exec -w /etc/caddy caddy caddy reload

reverse_proxy streams the body through unchanged and adds X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host. That keeps the signature intact. The handle /health block returns 404 to outside callers: the healthcheck runs inside the container, and there’s no reason to expose Redis status to the internet.

Alternative: Nginx with Certbot

If the VPS already runs Nginx, the model is the same, with the certificate issued by Certbot. Publish the app on loopback only (ports: ["127.0.0.1:3000:3000"]) and use something like:

server {
    listen 443 ssl;
    server_name webhook.yourcompany.com;

    ssl_certificate     /etc/letsencrypt/live/webhook.yourcompany.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/webhook.yourcompany.com/privkey.pem;

    client_max_body_size 4m;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Two things to watch. Use fullchain.pem, not cert.pem: the Certbot docs explain that fullchain.pem includes the intermediate certificates, and an incomplete chain is a classic reason for Meta to reject the URL. And raise client_max_body_size, whose Nginx default (1 MB) is smaller than the 3 MB a payload can reach. Also confirm that automatic renewal is scheduled (systemctl list-timers or a cron entry with certbot renew).

Deploy, test and update

docker compose up -d --build
docker compose ps    # app and redis should show as healthy

Test verification the way Meta does:

curl "https://webhook.yourcompany.com/webhook?hub.mode=subscribe&hub.verify_token=a-long-random-token&hub.challenge=12345"
# expected response: 12345

Then a signed POST, to prove the signature survives the proxy:

BODY='{"object":"whatsapp_business_account","entry":[]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | sed 's/^.* //')
curl -i -X POST "https://webhook.yourcompany.com/webhook" \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data "$BODY"
# expected: HTTP/2 200

To ship new code, docker compose up -d --build app worker recreates only those two services. Requests that fail during the swap come back through redelivery, and the worker deduplicates them.

Production checklist:

  • Domain with A/AAAA pointing to the VPS and ports 80/443 open in the provider’s firewall.
  • Persistent volumes for Caddy’s /data and for Redis.
  • VERIFY_TOKEN, APP_SECRET and PATH_SECRET only in .env, outside the repository.
  • Logs with max-size and max-file.
  • restart: unless-stopped on every service and Docker enabled on boot.
  • An external monitor hitting the public URL (a verification GET with the wrong token should return 403, not time out).

If you prefer Python, the same structure works with a FastAPI webhook in place of the Node app: the Dockerfile, Caddyfile and Compose file barely change.

How to do it with Vectalk

Vectalk is a proxy for the official Cloud API: it receives Meta’s webhooks and forwards them to the URLs you register, with the same payload Meta sends. The Meta side of the setup (app subscription on the account, fields, Live mode) is handled by the platform. On your side are exactly the pieces in this article.

According to the Vectalk webhooks documentation:

  • You register URLs in the dashboard, under the instance, or via API with POST https://apis.vectalk.com.br/api/webhooks, sending instance_id, url and name with a Bearer token.
  • You can register several URLs per instance, and all of them receive the same event. Handy for pointing production and staging at the same time.
  • Your endpoint must return 200 in under 20 seconds; otherwise delivery is retried. The receiver in this article responds in milliseconds.

The documentation doesn’t describe a signature header on forwarded events. In that case, leave APP_SECRET empty and set PATH_SECRET to a long random value: the registered URL becomes https://webhook.yourcompany.com/webhook/<secret>, and any request to another path gets a 404. A valid certificate is still required.

To learn how the API works, see the official WhatsApp API guide, the documentation, or create your account at apps.vectalk.com.br/register.

Frequently asked questions

Can I use a self-signed certificate for the WhatsApp webhook?

No. Meta’s documentation says the server needs a valid TLS certificate and that self-signed certificates are not supported. Caddy or Certbot issue free certificates that are accepted.

Does Docker restart a container when its healthcheck turns unhealthy?

Not through restart policies. They react when the container exits; the docs don’t treat the unhealthy status as a trigger. Use the healthcheck for depends_on and monitoring, and make the process exit with an error when it can’t recover.

How long does Meta retry a failed webhook?

According to the documentation, delivery is retried immediately and then a few more times with decreasing frequency for up to 7 days. That’s why the worker’s deduplication uses an 8-day TTL.

Do I need Redis just to receive webhooks?

It isn’t mandatory, but without a queue the processing happens inside the request, and any slowness in the database or an external API turns into redeliveries. With Redis persisted via AOF, the event is stored before the 200.


Official sources consulted on November 10, 2026: Create a webhook endpoint (Meta), Webhooks overview (Meta), Dockerfile HEALTHCHECK, Docker restart policies, json-file logging driver, Compose services, Docker and firewalls, Caddy: automatic HTTPS, Caddy: reverse_proxy, Official Caddy image, Certbot, BullMQ: Job IDs, Vectalk docs: Webhooks.

Try the official WhatsApp API today

Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.