I'm having trouble connecting my Spring Boot application to Redis in a Docker environment. While my application connects successfully to PostgreSQL in the same Docker network, Redis connections fail with:
Can you help me to fix this issue, so with that my API application will be able to send requests to Redis even inside the Docker.
Obs: If I run my Rest API application locally (not in docker) and I call any endpoint that use Redis, it works as expected, the issue is only inside docker.
message:
{
"apiPath": "uri=/v1/devices/38",
"errorCode": "INTERNAL_SERVER_ERROR",
"errorMessage": "Unable to connect to Redis",
"errorTime": "2025-03-28T16:57:26.309001832"
}
docker-compose:
version: '3.8'
services:
postgres:
image: postgres:latest
environment:
POSTGRES_DB: devicedb
POSTGRES_USER: admin
POSTGRES_PASSWORD: admin
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U admin"]
interval: 30s
timeout: 10s
retries: 5
redis:
image: "redis"
ports:
- "6379:6379"
command: redis-server --appendonly yes --requirepass admin # Added password requirement
healthcheck:
test: ["CMD", "redis-cli", "-a", "admin", "ping"] # Added auth for healthcheck
interval: 30s
timeout: 10s
retries: 5
app:
build: .
ports:
- "8080:8080"
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/devicedb
SPRING_DATASOURCE_USERNAME: admin
SPRING_DATASOURCE_PASSWORD: admin
SPRING_REDIS_HOST: redis
SPRING_REDIS_PORT: 6379
SPRING_REDIS_PASSWORD: admin
volumes:
postgres_data:
application.properties
spring.application.name=ManageDevices
server.port=8080
server.address=0.0.0.0
spring.datasource.url=jdbc:postgresql://postgres:5432/devicedb
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.redis.host=redis
spring.redis.port=6379
spring.redis.password=admin
The problem is that you are trying to connect to a redis container without bridging your host network with the container.
either add a network property or use localhost:
networks:
app-net:
driver: bridge
you then add a network property for bother services
networks:
- app-net
after that you'll be able to connect from your application using the container name redis
or using 127.0.0.1