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:
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.
1Configure Shared Postgres and Redis Service DNS Variables
.envPoint both the Node.js API and BullMQ worker to internal Docker service names "postgres" and "redis" so zero localhost connection failures occur.
.envdotenvNODE_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=63792Configure BullMQ Worker With maxRetriesPerRequest: null and SIGTERM Drain
src/worker.tsBullMQ 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.tstypescriptimport { 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); });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)yamlredis: image: redis:7-alpine command: redis-server --appendonly yes --maxmemory-policy noeviction4Launch and Scale BullMQ Workers Cleanly
terminalStart the stack, inspect health statuses, and scale BullMQ worker containers horizontally whenever queue backlog grows.
terminalbashdocker 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.
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.
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.
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"].
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:
Validate Node.js dotenv and native --env-file .env configs in your browser. Fix unquoted # truncation, duplicate keys, multiline PEM keys, and NODE_ENV bugs.
Generate a production Nginx reverse proxy for Node.js Express and PM2 on port 4000 with trust proxy, real client IP headers, Certbot SSL, and rate-limit safety.
Fix CORS preflight and cookie credential errors between Node.js Express APIs and Next.js App Router. Configure cors() middleware, app.options, and Helmet.
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.
Related Docker Compose Stack Guides
Browse all 10 Compose stacks →Docker Compose Node.js Express + MongoDB 7 Stack & Healthcheck Guide
Generate a Docker Compose stack for Node.js Express APIs and MongoDB 7 using mongosh ping healthchecks, authSource=admin URIs, and persistent named volumes.
Docker Compose FastAPI + PostgreSQL 16 + Celery Worker Healthcheck Guide
Build a production Docker Compose stack for Python FastAPI, PostgreSQL 16, Redis 7, and Celery workers with pg_isready healthchecks and Alembic migrations.
Docker Compose Next.js Standalone + Prisma + PostgreSQL 16 Stack Guide
Generate a Docker Compose config for Next.js App Router standalone output with Prisma ORM and PostgreSQL 16 using pg_isready healthchecks and service DNS.
Docker Compose Laravel + MySQL 8 + Redis Queue Stack & Healthcheck Guide
Generate a production Docker Compose file for Laravel 11/12 with MySQL 8, Redis 7, and queue:work using mysqladmin and redis-cli service_healthy probes.