How to Connect PHP to Redis with Docker Compose
Redis is the most common addition to a PHP development stack — caching, sessions, queues. It's also where a lot of people hit their first "why can't PHP see Redis?" wall after moving from a local install to Docker. Here's the full setup, and the one line that trips almost everyone up.
1. Add the Redis service
In compose.yml, add a redis service alongside your PHP and web server containers:
services:
php:
image: php:8.5-fpm
volumes:
- .:/var/www/html
redis:
image: redis:7
ports:
- "6379:6379"The ports: mapping is only there so you can reach Redis from your host machine (e.g. with a GUI client) — containers on the same Compose network don't need it to talk to each other.
2. The gotcha: use the service name, not localhost
This is the part that catches almost everyone. Inside a container, localhost or 127.0.0.1 refers to that container itself — not your host machine, and not the Redis container. Compose gives every service a DNS entry matching its service name, so from the php container, Redis is reachable at host redis, not localhost.
<?php
$redis = new Redis();
$redis->connect('redis', 6379); // service name, not 127.0.0.1
$redis->set('foo', 'bar');
echo $redis->get('foo');This requires the redis PECL extension in your PHP image. If you're building a custom Dockerfile (see Docker Compose vs Dockerfile), add:
RUN pecl install redis && docker-php-ext-enable redis
3. Symfony: configure the cache adapter
Point Symfony's Redis cache adapter at the service name via a DSN, ideally sourced from an environment variable so it stays configurable per environment:
# config/packages/cache.yaml
framework:
cache:
app: cache.adapter.redis
default_redis_provider: '%env(REDIS_URL)%'# .env REDIS_URL=redis://redis:6379
4. Laravel: set the host in .env
Laravel's default config/database.php Redis connection already reads from environment variables — you just need to point them at the service name:
# .env REDIS_HOST=redis REDIS_PORT=6379 REDIS_PASSWORD=null
5. Verify the connection
Before debugging application code, confirm Redis itself is reachable. Ping it directly from its own container:
docker compose exec redis redis-cli ping # PONG
Then confirm PHP can reach it across the network:
docker compose exec php php -r "var_dump((new Redis())->connect('redis', 6379));"
# bool(true)Common pitfalls
- Connecting to
127.0.0.1orlocalhostinstead of the service name — the single most common cause of "connection refused" in a containerized Redis setup. - Missing
depends_on— without it, nothing guarantees the Redis container has started before PHP tries to connect on the very first boot. - The
redisPHP extension isn't installed in the basephp:8.5-fpmimage — it has to be added explicitly, either via a custom Dockerfile or a library likepredis/predisthat needs no extension at all.
Generate a ready-to-run Docker Compose setup for your stack — compose.yml, nginx config, .env, and a README, in seconds.
Open the generator →