如何从Docker Compose获取Redis地址?Redis连接失败排查求助
Let's walk through the problems in your current config and fix them one by one:
1. Network Isolation Between Services
Your api service is attached to the proxy network, but your redis service isn't part of any user-defined network (it's using Docker Compose's default anonymous network). Services on separate networks can't reach each other by hostname, which is why you're seeing the ENOENT error.
Fix: Add the proxy network to your redis service so both services share the same network space.
2. Incorrect REDIS_URL Format
Most Redis clients expect a full connection URL with the protocol, hostname, and port—not just the hostname alone. Using only redis won't be recognized as a valid connection string by most libraries.
Fix: Update the REDIS_URL environment variable to redis://redis:6379.
3. Redis Readiness Check
The depends_on directive only ensures the redis container starts before api—it doesn't wait for Redis to finish initializing and be ready to accept connections. This can lead to connection failures if your API tries to connect before Redis is fully up.
Fix: Add a health check to the redis service, and configure api to wait for Redis to report as healthy.
Modified Docker Compose Config
version: '3.2' services: redis: image: 'bitnami/redis:latest' container_name: redis hostname: redis expose: - 6379 networks: - proxy # Added: Join the same network as the API environment: - ALLOW_EMPTY_PASSWORD=yes # Add this if you haven't set a Redis password (dev/test only) healthcheck: # Added: Verify Redis is ready to accept connections test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 3s retries: 5 api: image: tufanmeric/api:latest volumes: - /var/run/docker.sock:/var/run/docker.sock networks: - proxy environment: - REDIS_URL=redis://redis:6379 # Fixed: Full valid Redis connection URL depends_on: redis: condition: service_healthy # Modified: Wait for Redis to be healthy before starting deploy: mode: global labels: - 'traefik.port=3002' - 'traefik.frontend.rule=PathPrefix:/' - 'traefik.frontend.rule=Host:api.example.com' - 'traefik.docker.network=proxy' networks: proxy:
Quick Extra Check
Make sure your API application is actually reading the REDIS_URL environment variable to configure its Redis client—sometimes apps hardcode connection strings, so confirm it's pulling from the env var instead.
内容的提问来源于stack exchange,提问作者TufanMeric

