Docker Compose Builder · Node.js / BullMQ + Redis

Docker Compose Node.js + BullMQ Worker + Redis 7 + PostgreSQL 16 Guide

Generate a Compose Specification docker-compose.yml and matching .env.example for Node.js / BullMQ + Redis with native binary healthchecks, service_healthy boot ordering, and firewall-safe port bindings.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Runtime & Data Services

2. Healthchecks, Workers & Security

# docker-compose.yml — Modern Compose Specification (no obsolete 'version:' attribute)
# Generated by OpsCheck DevTools (Node.js / Express)
name: nodejs_bullmq_stack

services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "127.0.0.1:4000:4000"
    environment:
      DB_HOST: postgres
      DB_PORT: "5432"
      REDIS_HOST: redis
      REDIS_PORT: "6379"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - app_network

  worker:
    build:
      context: .
      dockerfile: Dockerfile
    command: node dist/worker.js
    restart: unless-stopped
    env_file:
      - .env
    environment:
      DB_HOST: postgres
      DB_PORT: "5432"
      REDIS_HOST: redis
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - app_network

  postgres:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${DB_DATABASE:-app_db}
      POSTGRES_USER: ${DB_USERNAME:-app}
      POSTGRES_PASSWORD: ${DB_PASSWORD:-change_me_strong}
    # Kept strictly internal on app_network (prevents Docker iptables UFW bypass)
    expose:
      - "5432"
    volumes:
      - db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-app} -d $${POSTGRES_DB:-app}"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 20s
    networks:
      - app_network

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

networks:
  app_network:
    driver: bridge

volumes:
  db_data:
  redis_data:
Service Boot Orderbridge: app_network
postgres(healthy)+redis(healthy)apiworker

Healthcheck & Security Diagnostics

Compose Spec v2+
  • passStartup Race Condition Prevented (condition: service_healthy)

    api and worker will wait until postgres and redis pass their native healthchecks before starting.

  • infoInternal Bridge DNS Hostnames (Never Use localhost Inside Containers)

    Connect over the shared app_network using Docker service names: DB_HOST=postgres (port 5432), REDIS_HOST=redis (port 6379). Inside the "api" container, 127.0.0.1/localhost points only to "api" itself and always refuses DB/broker connections.

  • passFirewall-Safe Port Exposure Enabled (127.0.0.1 / Internal expose:)

    Database and broker ports stay strictly isolated on app_network via expose:, and app ports bind to 127.0.0.1 so Docker never bypasses host UFW/nftables rules.

  • passNative Probe Binaries Used (pg_isready & redis-cli ping)

    Generated healthchecks invoke built-in service binaries rather than curl or wget, avoiding false "unhealthy" states in minimal Alpine and slim official images.

  • passPersistent Named Volumes Declared (db_data, redis_data)

    Top-level named volumes preserve database tables and broker queues across container rebuilds and "docker compose down" (data is only removed if you pass -v).

Runs locally in your browser. Compose YAML and environment templates are generated client-side.

Typical Container Boot & Connection Error (Node.js / BullMQ + Redis)

When depends_on lacks condition: service_healthy or internal service hostnames are misconfigured in .env, container logs typically surface this error during startup:

docker compose logs (Startup Failure)

Error: connect ECONNREFUSED 127.0.0.1:6379 at TCPConnectWrap.afterConnect [as oncomplete] (ioredis) — BullMQ Worker failed to connect

Container Boot Ordering, Bridge DNS & Persistence for Node.js / BullMQ + Redis

BullMQ powered by Redis 7 alongside a PostgreSQL 16 primary database is the gold-standard asynchronous job architecture for TypeScript and Node.js backends; handling transactional emails, Stripe webhook processing, report exports, and scheduled cron jobs reliably. Separating your HTTP API container (api) from your BullMQ processor container (worker) inside Docker Compose ensures CPU-heavy jobs never starve incoming REST latency.

Two Redis configuration traps frequently bite BullMQ deployments in Docker Compose. First, if the worker boots before Redis 7 and PostgreSQL 16 finish starting, ioredis spams MaxRetriesPerRequestError or ECONNREFUSED logs during cold boots. Second, BullMQ strictly requires Redis maxmemory-policy to be set to noeviction and append-only persistence (appendonly yes) enabled on a named redis_data volume; otherwise Redis silently evicts BullMQ job keys under memory pressure and corrupts active queues.

Adding native pg_isready and redis-cli ping healthchecks with condition: service_healthy guarantees both the Node.js API and BullMQ worker wait cleanly until PostgreSQL and Redis are ready to process traffic. Sharing the same built Dockerfile image across both services while overriding only command: node dist/worker.js keeps your TypeScript types and job payloads 100% synchronized.

Inside both containers, configure ioredis with host: process.env.REDIS_HOST ("redis") and maxRetriesPerRequest: null (a mandatory BullMQ requirement on Worker connections) so long-running blocking Redis BRPOPLPUSH/BZPOPMIN calls never throw timeout errors.

Finally, locking PostgreSQL (5432) and Redis (6379) behind expose: on app_network protects your BullMQ job queues from unauthorized external access; which is especially critical because unauthenticated Redis instances exposed on 0.0.0.0:6379 are compromised within minutes on public VPS hosts.

As BullMQ job volume scales in Docker Compose, monitor Redis memory usage (docker compose exec redis redis-cli info memory) and configure BullMQ removeOnComplete and removeOnFail retention caps so completed job payloads never bloat Redis RAM indefinitely. Combining noeviction persistence, native redis-cli and pg_isready healthchecks, and graceful SIGTERM worker draining ensures zero lost background jobs across deployments.

Step-by-Step Node.js / BullMQ + Redis Docker Compose Setup Guide

Follow each step below to pair the generated Compose file with accurate container DNS variables, safe database migrations, and zero-downtime restarts.

  1. 1Configure Shared Postgres and Redis Service DNS Variables

    .env

    Point both the Node.js API and BullMQ worker to internal Docker service names "postgres" and "redis" so zero localhost connection failures occur.

    .envdotenv
    NODE_ENV=production
    APP_PORT=4000
    DB_DATABASE=app_db
    DB_USERNAME=app
    DB_PASSWORD=change_me_strong
    DATABASE_URL="postgresql://app:change_me_strong@postgres:5432/app_db"
    REDIS_HOST=redis
    REDIS_PORT=6379
  2. 2Configure BullMQ Worker With maxRetriesPerRequest: null and SIGTERM Drain

    src/worker.ts

    BullMQ requires maxRetriesPerRequest: null on ioredis worker connections. Hook SIGTERM to call worker.close() so docker compose down waits for active jobs to finish before exiting.

    src/worker.tstypescript
    import { Worker } from 'bullmq';
    import IORedis from 'ioredis';
    
    const connection = new IORedis({
      host: process.env.REDIS_HOST ?? 'redis',
      port: Number(process.env.REDIS_PORT ?? 6379),
      maxRetriesPerRequest: null,
    });
    
    const worker = new Worker(
      'emails',
      async (job) => {
        console.log('Processing job', job.id, job.data);
      },
      { connection, concurrency: 5 }
    );
    
    process.on('SIGTERM', async () => {
      await worker.close();
      await connection.quit();
      process.exit(0);
    });
  3. 3Enforce Redis noeviction Policy for BullMQ Queue Integrity

    docker-compose.yml (redis command override)

    Append --maxmemory-policy noeviction alongside --appendonly yes so Redis never evicts pending BullMQ job metadata under memory pressure.

    docker-compose.yml (redis command override)yaml
      redis:
        image: redis:7-alpine
        command: redis-server --appendonly yes --maxmemory-policy noeviction
  4. 4Launch and Scale BullMQ Workers Cleanly

    terminal

    Start the stack, inspect health statuses, and scale BullMQ worker containers horizontally whenever queue backlog grows.

    terminalbash
    docker compose up -d --build
    docker compose ps
    docker compose up -d --scale worker=3

Common Node.js / BullMQ + Redis Docker Compose Pitfalls

Avoid these three container orchestration mistakes before deploying your Compose stack onto staging or production servers.

Pitfall 1

Using Redis allkeys-lru Eviction Policy With BullMQ

Standard cache presets use allkeys-lru, which silently deletes BullMQ job locks and queue pointers when memory fills up; causing stalled jobs and lost work. Always keep BullMQ on a dedicated Redis with maxmemory-policy noeviction.

Pitfall 2

Omitting maxRetriesPerRequest: null in ioredis for BullMQ Workers

BullMQ uses blocking Redis commands that wait indefinitely for new jobs. If ioredis keeps its default maxRetriesPerRequest: 20, BullMQ throws a fatal startup error or disconnects repeatedly.

Pitfall 3

Exposing Redis 6379 Without Authentication on a Cloud VPS

Publishing "6379:6379" without 127.0.0.1 exposes Redis globally through Docker iptables rules, allowing attackers to overwrite BullMQ queues or inject arbitrary jobs. Keep Redis internal via expose: ["6379"].

Related Tools

Pair Your Docker Compose Stack With .env Linting, Nginx TLS & CORS Checks

Validate your .env file for unescaped $$ interpolation or leaked secrets, configure Nginx DNS resolution, and verify cross-origin headers:

Frequently Asked Questions

Why does BullMQ fail with ECONNREFUSED 127.0.0.1:6379 in Docker Compose?
ioredis defaults to 127.0.0.1 when no host option is passed. Pass host: process.env.REDIS_HOST ("redis") explicitly in both Queue and Worker constructors.
Can I scale the worker service to multiple containers with docker compose up --scale worker=3?
Yes. Because the worker service does not publish any host ports, Docker Compose lets you scale worker containers horizontally while all instances pull jobs safely from Redis using atomic Lua scripts.
How long does Docker wait for BullMQ to finish an active job during docker compose down?
Docker waits 10 seconds (stop_grace_period: 10s) before sending SIGKILL. If your BullMQ jobs take up to 45 seconds, add stop_grace_period: 60s to the worker service so worker.close() finishes cleanly.
Should BullMQ and application caching share the same Redis container?
For small workloads you can use separate key prefixes, but in production keep BullMQ on a dedicated Redis instance configured with noeviction + AOF persistence while ephemeral HTTP caches use an LRU Redis instance.
Browse all 10 Compose stacks →