I am trying to do a basic docker container(s) with spring boot and MongoDB and redis. Mongo is just fine but connection can't be established between redis and spring boot although the configuration looks ok to me.
docker-compose.yml
version: "3.9"
services:
web:
build: .
ports:
- "1234:1234"
depends_on:
- redis
- db
db:
image: mongo
hostname: mongodb
ports:
- "27017:27017"
redis:
hostname: redis
image: redis
restart: always
ports:
- "6379:6379"
Dockerfile:
FROM adoptopenjdk:11
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
Config.java:
@Configuration
@EnableRedisRepositories
public class Config
{
RedisStandaloneConfiguration standaloneConfiguration() {
return new RedisStandaloneConfiguration("redis", 6379);
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory(standaloneConfiguration());
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
Problem: All the containers are running after docker compose up. but the connection between spring and redis can't be established.
java.net.ConnectException: Connection refused (Connection refused)
slot-web-1 | at java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]
slot-web-1 | at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399) ~[na:na]
slot-web-1 | at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242) ~[na:na]
slot-web-1 | at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224) ~[na:na]
slot-web-1 | at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:na]
localhostinstead ofredis?docker compose down && docker compose up -d redis && sleep 5 && docker compose up --build -ddepends_ononly guarantees that the container is started first, but not that the service (contained within the container) is started before the depending container is started.