I have one eureka Server that has multiple clients, I have deployed the micro services to to a docker container, whenever I do docker compose pull, and do docker compose up -d, Eureka server starts on http://localhost:8761/eureka/ instead of 'http://eureka-server:8761/eureka/. What am I doing wrong in setting the eureka to use the docker config instead of the local
This is my Eureka-Server Config
spring:
application:
name: eureka-server
zipkin:
base-url: http://zipkin:9411
server:
ports:
- "8761:8761"
eureka:
client:
fetch-registry: false
register-with-eureka: false
The APiGW Docker config
server:
port: 8083
spring:
application:
name: api-gateway
zipkin:
base-url: http://zipkin:9411
cloud:
gateway:
routes:
- id: customer
uri: lb://CUSTOMER
predicates:
- Path=/api/v1/customers/**
eureka:
client:
serviceUrl:
defaultZone: http://eureka-server:8761/eureka
fetch-registry: true
register-with-eureka: true
My Docker Compose file
services:
postgres:
container_name: postgres
build:
context: .
dockerfile: Dockerfile-db
image: postgres
environment:
POSTGRES_USER: ornaccode
POSTGRES_PASSWORD: password
PGDATA: /data/postgres
volumes:
- postgres:/data/postgres
ports:
- "5432:5432"
networks:
- postgres
restart: unless-stopped
pgadmin:
container_name: pgadmin
image: dpage/pgadmin4
environment:
PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4#pgadmin.org}
PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
PGADMIN_CONFIG_SERVER_MODE: 'False'
volumes:
- pgadmin:/var/lib/pgadmin
ports:
- "5050:80"
networks:
- postgres
restart: unless-stopped
zipkin:
image: openzipkin/zipkin
container_name: zipkin
ports:
- "9411:9411"
networks:
- spring
rabbitmq:
image: rabbitmq:3.9.11-management-alpine
container_name: rabbitmq
ports:
- "5672:5672"
- "15672:15672"
networks:
- spring
eureka-server:
image: remymumoh/eureka-server:latest
container_name: eureka-server
ports:
- "8761:8761"
environment:
- SPRING_PROFILES_ACTIVE=docker
networks:
- spring
depends_on:
- zipkin
apigw:
image: remymumoh/apigw:latest
container_name: apigw
ports:
- "8083:8083"
environment:
- SPRING_PROFILES_ACTIVE=docker
networks:
- spring
depends_on:
- zipkin
- eureka-server
customer:
image: remymumoh/customer:latest
container_name: customer
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=docker
networks:
- spring
- postgres
depends_on:
- zipkin
- eureka-server
- postgres
- rabbitmq
fraud:
image: remymumoh/fraud:latest
container_name: fraud
ports:
- "8081:8081"
environment:
- SPRING_PROFILES_ACTIVE=docker
networks:
- spring
- postgres
depends_on:
- zipkin
- eureka-server
- postgres
- rabbitmq
notification:
image: remymumoh/notification:latest
container_name: notification
ports:
- "8082:8082"
environment:
- SPRING_PROFILES_ACTIVE=docker
networks:
- spring
- postgres
depends_on:
- zipkin
- eureka-server
- postgres
- rabbitmq
networks:
postgres:
driver: bridge
spring:
driver: bridge
volumes:
postgres:
pgadmin:
My Error log
Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://eureka-server:8761/eureka/}, exception=I/O error on GET request for "http://eureka-server:8761/eureka/apps/": Connect to eureka-server:8761 [eureka-server/172.29.0.4] failed: Connection refused; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to eureka-server:8761 [eureka-server/172.29.0.4] failed: Connection refused stacktrace=org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://eureka-server:8761/eureka/apps/": Connect to eureka-server:8761 [eureka-server/172.29.0.4] failed: Connection refused; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to eureka-server:8761 [eureka-server/172.29.0.4] failed: Connection refused
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
at org.springframework.cloud.netflix.eureka.http.RestTemplateEurekaHttpClient.getApplicationsInternal(RestTemplateEurekaHttpClient.java:145)
at org.springframework.cloud.netflix.eureka.http.RestTemplateEurekaHttpClient.getApplications(RestTemplateEurekaHttpClient.java:135)
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$6.execute(EurekaHttpClientDecorator.java:137)
at com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient.executeOnNewServer(RedirectingEurekaHttpClient.java:121)
at com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient.execute(RedirectingEurekaHttpClient.java:80)
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134)
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$6.execute(EurekaHttpClientDecorator.java:137)
at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:120)
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134)
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$6.execute(EurekaHttpClientDecorator.java:137)
at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77)
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134)
at com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry(DiscoveryClient.java:1101)
at com.netflix.discovery.DiscoveryClient.fetchRegistry(DiscoveryClient.java:1014)
at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:441)
at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:283)
at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:279)
at org.springframework.cloud.netflix.eureka.CloudEurekaClient.<init>(CloudEurekaClient.java:66)
at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.eurekaClient(EurekaClientAutoConfiguration.java:295)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$1(AbstractBeanFactory.java:374)
at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:376)
at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:179)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:371)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.getTargetObject(EurekaRegistration.java:127)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.getEurekaClient(EurekaRegistration.java:115)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:282)
at org.springframework.cloud.context.scope.GenericScope$LockedScopedProxyFactoryBean.invoke(GenericScope.java:485)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration$$EnhancerBySpringCGLIB$$1991a9f7.getEurekaClient(<generated>)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.maybeInitializeClient(EurekaServiceRegistry.java:54)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(EurekaServiceRegistry.java:38)
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaAutoServiceRegistration.start(EurekaAutoServiceRegistration.java:83)
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
at java.base/java.lang.Iterable.forEach(Iterable.java:75)
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:64)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:765)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:445)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343)
at com.ornac.apigw.ApiGWApplication.main(ApiGWApplication.java:11)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to eureka-server:8761 [eureka-server/172.29.0.4] failed: Connection refused
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:156)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:776)
... 68 more
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:633)
at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:75)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
When I do http://localhost:8761/eureka/ on the browser, I can reach the eureka-server but when I use the URL for docker http://eureka-server:8761/eureka/ I am not able. Any help is appreciated.
Add hostname like:
eureka-server:
image: remymumoh/eureka-server:latest
container_name: eureka-server
hostname: eureka-server
I have 2 Springboot microservices, one is the Eureka server and the other one is the Gateway.
I can't find the right configuration to make the Gateway register to the Eureka server.
This is the eureka.yml with the K8s configuration:
Eureka.yml
apiVersion: v1
kind: ConfigMap
metadata:
name: eureka-cm
data:
eureka_service_address: http://eureka-0.eureka:8761/eureka
---
apiVersion: v1
kind: Service
metadata:
name: eureka
labels:
app: eureka
spec:
clusterIP: None
ports:
- port: 8761
name: eureka
selector:
app: eureka
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: eureka
spec:
serviceName: "eureka"
replicas: 1
selector:
matchLabels:
app: eureka
template:
metadata:
labels:
app: eureka
spec:
containers:
- name: eureka
image: myrepo/eureka1.0:eureka
imagePullPolicy: Always
ports:
- containerPort: 8761
env:
- name: EUREKA_SERVER_ADDRESS
valueFrom:
configMapKeyRef:
name: eureka-cm
key: eureka_service_address
---
apiVersion: v1
kind: Service
metadata:
name: eureka-lb
labels:
app: eureka
spec:
selector:
app: eureka
type: NodePort
ports:
- port: 80
targetPort: 8761
Eureka.application.yml
spring:
application:
name: eureka
server:
port: 8761
eureka:
instance:
hostname: "${HOSTNAME}.eureka"
client:
register-with-eureka: false
fetch-registry: false
serviceUrl:
defaultZone: ${EUREKA_SERVER_ADDRESS}
Gateway.yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: cloud-gateway-app
labels:
app: cloud-gateway-app
spec:
replicas: 1
selector:
matchLabels:
app: cloud-gateway-app
template:
metadata:
labels:
app: cloud-gateway-app
spec:
containers:
- name: cloud-gateway-app
image: myrepo/gateway1.0:gateway
imagePullPolicy: Always
ports:
- containerPort: 9191
---
apiVersion: v1
kind: Service
metadata:
name: cloud-gateway-svc
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 9191
protocol: TCP
selector:
app: cloud-gateway-app
Gateway.application.yml
eureka:
instance:
preferIpAddress: true
hostname: eureka-0
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://eureka-0.eureka.default.svc.cluster.local:8761/eureka
This is the error I got when I check the logs of the Gateway's pod:
error on POST request for "http://eureka-0.eureka.default.svc.cluster.local:8761/eureka/apps/API-GATEWAY": eureka-0.eureka.default.svc.cluster.local; nested exception is java.net.UnknownHostException: eureka-0.eureka.default.svc.cluster.local
Following the documentation I've tried to set defaultZone property of the Gateway.application.properties file following this pattern:
172-17-0-3.default.pod.cluster.local:8761/eureka
But in this way too, I can't subscribe to the Eureka Server.
I resolved by modifying the Gateway.application.yml in this way:
eureka:
instance:
preferIpAddress: true
hostname: eureka-0
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://eureka-0.eureka:8761/eureka/
EDIT:
I'm encountering some problems in registering other microservices to the Eureka Server.
I've tried by increasing the replicas of the Eureka Server and made each microservice register to a dedicated replica, but as now this is not working.
I was trying out spring boot microservice deployment on kubernetes cluster using Helm Chart. But I noticed a strange issue that my spring boot application start but it shutdown immediately after
Here are the logs
Started JhooqK8sApplication in 3.431 seconds (JVM running for 4.149)
2020-06-25 20:57:24.460 INFO 1 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-06-25 20:57:24.469 INFO 1 --- [extShutdownHook] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#548a102f{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
2020-06-25 20:57:24.470 INFO 1 --- [extShutdownHook] org.eclipse.jetty.server.session : node0 Stopped scavenging
2020-06-25 20:57:24.474 INFO 1 --- [extShutdownHook] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'
2020-06-25 20:57:24.493 INFO 1 --- [extShutdownHook] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext#56528192{application,/,[file:///tmp/jetty-docbase.4637295322181051129.8080/],UNAVAILABLE}
Spring Boot Version : 2.2.7.RELEASE
Docker Hub Public image for spring boot : rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty
One strange thing which i noticed when i use kubectl command manually to create deployment and service spring boot deployments goes perfectly fine.
vagrant#kmaster:~$ kubectl create deployment demo --image=rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty
vagrant#kmaster:~$ kubectl expose deployment demo --type=LoadBalancer --name=demo-service --external-ip=1.1.1.1 --port=8080
(I followed this guide for deploying spring boot on kubernete - Deploy spring boot on kubernetes cluster)
I am just wodering is there something wrong with spring boot or my helm setup?
Here is my helm templates -
---
# Source: springboot/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: RELEASE-NAME-springboot
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
---
# Source: springboot/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: RELEASE-NAME-springboot
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
spec:
type: ClusterIP
ports:
- port: 80
targetPort: http
protocol: TCP
name: http
selector:
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
---
# Source: springboot/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: RELEASE-NAME-springboot
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
template:
metadata:
labels:
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
spec:
serviceAccountName: RELEASE-NAME-springboot
securityContext:
{}
containers:
- name: springboot
securityContext:
{}
image: "rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty"
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{}
---
# Source: springboot/templates/tests/test-connection.yaml
apiVersion: v1
kind: Pod
metadata:
name: "RELEASE-NAME-springboot-test-connection"
labels:
helm.sh/chart: springboot-0.1.0
app.kubernetes.io/name: springboot
app.kubernetes.io/instance: RELEASE-NAME
app.kubernetes.io/version: "1.16.0"
app.kubernetes.io/managed-by: Helm
annotations:
"helm.sh/hook": test-success
spec:
containers:
- name: wget
image: busybox
command: ['wget']
args: ['RELEASE-NAME-springboot:80']
restartPolicy: Never
2020-06-25 20:57:24.469 INFO 1 --- [extShutdownHook] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#548a102f{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
ports:
- name: http
containerPort: 80
It appears the liveness probe (configured to contact the port named http) is killing your Pod since your container appears to be listening on :8080 but you've told kubernetes that it's listening on :80
Since a kubectl created deployment will not have any such specificity, kubernetes won't use a liveness probe and there you are
You can usually configure the spring application via an environment variable if you want to test that theory:
containers:
- name: springboot
env:
- name: SERVER_PORT
value: '80'
# and its friend, which is the one that
# you should be using for liveness and readiness
- name: MANAGEMENT_SERVER_PORT
value: '8080'
securityContext:
{}
image: "rahulwagh17/kubernetes:jhooq-k8s-springboot-jetty"
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 80
protocol: TCP
I had a previous question that (I think at least) that more or less became useless as I managed to fix the errors I was presented with.. However my new error, is that I cannot seem to connect to mongodb from within my docker image
docker-compose.yml:
version: '3.1'
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mongo
ports:
- 8080:8080
mongo:
image: mongo
ports:
- '27017:27017'
networks:
mongo_net:
ipv4_address: 172.28.0.2
networks:
mongo_net:
driver: bridge
ipam:
driver: default
config:
-
subnet: 172.28.0.2/24
application.properties:
spring.data.mongodb.database=myDb
spring.data.mongodb.host=172.28.0.2
spring.data.mongodb.port=27017
And the actual error:
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.4.jar!/:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.4.jar!/:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.4.jar!/:na]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_111]
Caused by: java.net.SocketTimeoutException: connect timed out
You’ve explicitly created a network in your docker-compose.yml file, and set your database to use that network. Docker Compose also creates a default network for you, and since your application doesn’t explicitly declare any networks, that attaches to only the default network. Then the two containers are on different networks and the one can’t reach the other.
The easiest solution here is to just delete all of the manual network configuration:
version: '3.1'
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
depends_on:
- mongo
ports:
- '8080:8080'
mongo:
image: mongo
ports:
- '27017:27017'
The name of the service block will be a valid DNS hostname, and in your configuration you can set spring.data.mongodb.host=mongo.
I agree David answer is right. But here is a takeaway, your configuration works too, I tried with my sample and here is the result.
Issue is your app is not attached to the network.
services:
company-repo-docker-app:
image: company-repo-image
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mongo
ports:
- 8080:8080
networks:
- mongo_net
sample docker-compose.yml
version: '3.1'
services:
mongo-app:
image: barath-mongo
ports:
- "9000:9000"
depends_on:
- mongo
environment:
SPRING_DATA_MONGODB_PORT: 27017
SPRING_DATA_MONGODB_HOST: 172.28.0.2
SPRING_DATA_MONGODB_DATABASE: myDb
networks:
- mongo_net
mongo:
image: mongo
ports:
- '27017:27017'
networks:
mongo_net:
ipv4_address: 172.28.0.2
networks:
mongo_net:
driver: bridge
ipam:
driver: default
config:
-
subnet: 172.28.0.2/24
mongo container ip address:
$ docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' ec2-user_mongo_1
172.28.0.2
docker network settings
"IPAM": {
"Driver": "default",
"Options": null,
"Config": [
{
"Subnet": "172.28.0.2/24"
}
]
},
"Internal": false,
"Attachable": true,
"Ingress": false,
"ConfigFrom": {
"Network": ""
},
"ConfigOnly": false,
"Containers": {
"02b8b4148dd830eaddeb7e9ebd6305a6ae3c106bae5a495103c632aec7999274": {
"Name": "ec2-user_mongo-app_1",
"EndpointID": "885088d551888e1dec95b1c0e337c6a4b84f1bb2aebc4407963d3c0b4f6ec09d",
"MacAddress": "02:42:ac:1c:00:03",
"IPv4Address": "172.28.0.3/24",
"IPv6Address": ""
},
"3e4266fca3c8163412cc1c4733cad004aa0f366dc9fe30d03c7ecafe87b4e826": {
"Name": "ec2-user_mongo_1",
"EndpointID": "a6a72c7fc314a294c53d5c394ac1757702a0a95c588af2f730e971953dbbaa5f",
"MacAddress": "02:42:ac:1c:00:02",
"IPv4Address": "172.28.0.2/24",
"IPv6Address": ""
}
},
output :
ongo-app_1 | 2019-01-28 17:07:29.710 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:1}] to 172.28.0.2:27017
mongo-app_1 | 2019-01-28 17:07:29.735 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=172.28.0.2:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 5]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=20314562}
mongo-app_1 | 2019-01-28 17:07:29.742 INFO 1 --- [72.28.0.2:27017] org.mongodb.driver.cluster : Discovered cluster type of STANDALONE
mongo-app_1 | 2019-01-28 17:07:30.387 INFO 1 --- [ main] com.barath.app.service.CustomerService : Saving the customer with customer details com.barath.app.document.Customer#37654521
mongo_1 | 2019-01-28T17:07:30.488+0000 I NETWORK [listener] connection accepted from 172.28.0.3:56250 #2 (2 connections now open)
mongo_1 | 2019-01-28T17:07:30.491+0000 I NETWORK [conn2] received client metadata from 172.28.0.3:56250 conn2: { driver: { name: "mongo-java-driver", version: "3.8.2" }, os: { type: "Linux", name: "Linux", architecture: "amd64", version: "4.14.77-81.59.amzn2.x86_64" }, platform: "Java/Oracle Corporation/1.8.0_191-b12" }
mongo-app_1 | 2019-01-28 17:07:30.497 INFO 1 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:2}] to 172.28.0.2:27017
mongo_1 | 2019-01-28T17:07:30.576+0000 I STORAGE [conn2] createCollection: myDb.customer with generated UUID: 6bd5b022-16b6-4a04-96b0-d94988155a53
mongo-app_1 | 2019-01-28 17:07:31.514 INFO 1 --- [ main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
mongo-app_1 | 2019-01-28 17:07:31.879 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
mongo-app_1 | 2019-01-28 17:07:32.372 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
mongo-app_1 | 2019-01-28 17:07:32.432 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
mongo-app_1 | 2019-01-28 17:07:32.522 INFO 1 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
mongo-app_1 | 2019-01-28 17:07:32.977 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9000 (http) with context path ''
mongo-app_1 | 2019-01-28 17:07:32.984 INFO 1 --- [ main] com.barath.app.Application : Started Application in 11.151 seconds (JVM running for 13.149)
I'm trying to launch my SpringBoot application without configuring DataSource prior to compilation. If I do this, indicating the parameters, the application works normally, but I want to pass them through the JAVA_OPTS parameter when I run a docker container. Like that:
docker run --network public --link pg --name tm -e JAVA_OPTS="-Ddatasource.jdbcUrl=jdbc:postgresql://pg:5432/ggal1701 -Ddatasource.user=postgres -Ddatasource.password=postgres" -p 9000:8080 worker
I've tried many of the options I've seen on Stackoverflow, but none of them worked for me.
My build.gradle:
buildscript {
repositories {
mavenLocal()
jcenter()
maven { url 'http://repo.spring.io/plugins-release' }
maven { url 'http://repo.spring.io/milestone' }
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath group: 'net.ltgt.gradle', name: 'gradle-apt-plugin', version: '0.6'
classpath group: 'org.springframework.boot', name: 'spring-boot-gradle-plugin', version: spring_boot_version
classpath group: 'org.springframework.build.gradle', name: 'propdeps-plugin', version: '0.0.7'
}
}
plugins {
id "org.sonarqube" version "2.6.2"
}
apply plugin: "org.sonarqube"
apply plugin: 'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8
apply plugin: 'maven'
apply plugin: 'spring-boot'
apply plugin: 'war'
apply plugin: 'propdeps'
defaultTasks 'bootRun'
bootRepackage {
mainClass = 'es.asd.GGAL1701.Application'
}
war {
rootSpec.exclude("**/tomcat-*.jar")
exclude("**/client")
exclude("**/tmp")
exclude("**/upload")
from "dist"
}
springBoot {
mainClass = 'es.asd.GGAL1701.Application'
executable = true
}
bootRun {
addResources = false
}
if (project.hasProperty('prod')) {
apply from: 'gradle/profile_prod.gradle'
} else {
apply from: 'gradle/profile_dev.gradle'
}
apply from: 'gradle/process_resources.gradle'
group = 'es.asd.GGAL1701'
version = '0.0.1-SNAPSHOT'
description = ''
configurations {
providedRuntime
}
repositories {
maven {
url "http://asd-nexus.com/repository/maven-central/"
credentials {
username "asd"
password "asd./"
}
}
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: "${nexusUrl}/repository/maven-releases/") {
authentication(userName: nexusUsername, password: nexusPassword)
}
snapshotRepository(url: "${nexusUrl}/repository/maven-snapshots") {
authentication(userName: nexusUsername, password: nexusPassword)
}
}
}
}
repositories {
mavenLocal()
maven { url 'http://repo.spring.io/milestone' }
maven { url 'http://repo.spring.io/snapshot' }
maven { url 'https://repository.jboss.org/nexus/content/repositories/releases' }
maven { url 'https://oss.sonatype.org/content/repositories/releases' }
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
maven { url 'http://repo.maven.apache.org/maven2' }
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-logging'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
//
compile group: 'javax.inject', name: 'javax.inject', version: '1'
compile group: 'javax.el', name: 'javax.el-api', version: '3.0.0'
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
compile group: 'javax.transaction', name: 'javax.transaction-api', version: '1.2'
compile group: 'javax.annotation', name: 'jsr250-api', version: '1.0'
compile(group: 'com.zaxxer', name: 'HikariCP', version: '2.6.3') {
exclude(module: 'tools')
}
compile group: 'org.postgresql', name: 'postgresql', version: postgresql_version
compile group: 'org.springframework', name: 'spring-aspects', version: spring_framework_version
compile group: 'org.springframework.data', name: 'spring-data-jpa', version: spring_framework_data_version
compile group: 'org.springframework.security', name: 'spring-security-core', version: spring_security_version
compile group: 'org.springframework.security', name: 'spring-security-config', version: spring_security_version
compile group: 'org.springframework.security', name: 'spring-security-data', version: spring_security_version
compile group: 'org.springframework.security', name: 'spring-security-web', version: spring_security_version
compile group: 'org.springframework.boot', name: 'spring-boot-autoconfigure', version: spring_boot_version
compile group: 'org.hibernate', name: 'hibernate-core', version: hibernate_version
compile group: 'org.hibernate', name: 'hibernate-java8', version: hibernate_version
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: hibernate_version
compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.7.0'
compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-yaml', version: jackson_version
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: jackson_version
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: jackson_version
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5', version: jackson_version
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: jackson_version
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.5'
compile group: 'net.bull.javamelody', name: 'javamelody-core', version: '1.68.0'
compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.2'
// Envío de emails
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
// Generación de PDFs
compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.10'
}
compileJava.dependsOn(processResources)
clean {
delete "target"
}
task wrapper(type: Wrapper) {
gradleVersion = '2.12'
}
task stage(dependsOn: 'bootRepackage') {
}
My gradle.properties:
rootProject.name=application
profile=dev
##
## Versiones de las dependencias comunes del proyecto
postgresql_version=9.4-1203-jdbc42
jackson_version=2.7.9
hibernate_version=5.2.10.Final
spring_boot_version=1.4.7.RELEASE
spring_framework_version=4.3.9.RELEASE
spring_framework_data_version=1.10.11.RELEASE
spring_security_version=4.1.4.RELEASE
systemProp.sonar.host.url=https://asd-sonarqube.ga
systemProp.sonar.login=asd
systemProp.sonar.password=asd./
systemProp.sonar.sources=src/main
nexusUrl=http://asd-nexus.ga
nexusUsername=asd
nexusPassword=asd./
#Para solucionar problema de lanzar sonarqube desde jenkins
org.gradle.daemon=false
#systemProp.sonar.jdbc.url=jdbc:postgresql://localhost/sonar
#systemProp.sonar.jdbc.username=sonar
#systemProp.sonar.jdbc.password=sonar
##
## Configuraciones de GRADLE
##
## Below are some of the gradle performance improvement settings that can be used as required, these are not enabled by default
##
## The Gradle daemon aims to improve the startup and execution time of Gradle.
## When set to true the Gradle daemon is to run the build.
## TODO: disable daemon on CI, since builds should be clean and reliable on servers
## un comment the below line to enable the daemon
#org.gradle.daemon=true
## Specifies the JVM arguments used for the daemon process.
## The setting is particularly useful for tweaking memory settings.
## Default value: -Xmx1024m -XX:MaxPermSize=256m
## un comment the below line to override the daemon defaults
#org.gradle.jvmargs=-Xmx1024m -XX:MaxPermSize=256m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
## When configured, Gradle will run in incubating parallel mode.
## This option should only be used with decoupled projects. More details, visit
## http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
## un comment the below line to enable parellel mode
#org.gradle.parallel=true
## Enables new incubating mode that makes Gradle selective when configuring projects.
## Only relevant projects are configured which results in faster builds for large multi-projects.
## http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:configuration_on_demand
## un comment the below line to enable the selective mode
#org.gradle.configureondemand=true
My application.yml:
# ===================================================================
# Spring Boot configuration.
#
# This configuracion will be overriden by the Spring profile you use,
# for example application-dev.yml if you use the "dev" profile.
# ===================================================================
locale:
default: es
server:
port: 8080
spring:
jpa:
database-platform: org.hibernate.dialect.PostgreSQL94Dialect
database: POSTGRESQL
openInView: false
show_sql: false
generate-ddl: false
hibernate:
ddl-auto: none
naming-strategy: org.hibernate.cfg.EJB3NamingStrategy
properties:
hibernate.cache.use_second_level_cache: false
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
hibernate.id.new_generator_mappings: true
hibernate.current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
http:
multipart:
max-file-size: 20Mb
max-request-size: 20Mb
messages:
basename: i18n/messages
thymeleaf:
mode: XHTML
properties:
async:
corePoolSize: 2
maxPoolSize: 50
queueCapacity: 10000
security:
authentication:
jwt:
secret: c2t3f0c5dXF6bV9tOV45X2RpdmlzYQ==
# Token is valid 24 hours
tokenValidityInSeconds: 86400
tokenValidityInSecondsForRememberMe: 2592000
My application-prod.yml:
# ===================================================================
# Spring Boot configuration for the "prod" profile.
#
# This configuracion overrides the application.yml file.
# ===================================================================
spring:
# Configuración de la BASE DE DATOS
datasource:
dataSourceClassName: org.postgresql.ds.PGSimpleDataSource
url: jdbc:postgresql://pg:5432/ggal1701
username: asd
password: asd
maximum-pool-size: 5
application:
url: http://localhost:8080
profiles:
active: prod
devtools:
restart:
enabled: false
livereload:
enabled: false
server:
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,text/css, application/javascript, application/json
As I mentioned at the beginning, I have tried many of the alternatives that appear in StackOverflow, but when I don't configure spring.datasource in my application-prod.yml, I always get a bug similar to the following one:
mrnobody#mrnobody-UX301LAA:~/Escritorio/tfg/appserver$ sudo docker run --network public --link pg --name tm -e JAVA_OPTS="-Ddatasource.jdbcUrl=jdbc:postgresql://pg:5432/ggal1701 -Ddatasource.user=postgres -Ddatasource.password=postgres" -p 9000:8080 worker
02-May-2018 20:56:17.864 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/8.0.51
02-May-2018 20:56:17.867 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built: Apr 9 2018 21:20:15 UTC
02-May-2018 20:56:17.868 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number: 8.0.51.0
02-May-2018 20:56:17.868 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name: Linux
02-May-2018 20:56:17.868 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Version: 4.13.0-39-generic
02-May-2018 20:56:17.868 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Architecture: amd64
02-May-2018 20:56:17.868 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Java Home: /usr/lib/jvm/java-8-openjdk-amd64/jre
02-May-2018 20:56:17.869 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Version: 1.8.0_162-8u162-b12-1~deb9u1-b12
02-May-2018 20:56:17.869 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log JVM Vendor: Oracle Corporation
02-May-2018 20:56:17.869 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_BASE: /usr/local/tomcat
02-May-2018 20:56:17.869 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log CATALINA_HOME: /usr/local/tomcat
02-May-2018 20:56:17.870 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties
02-May-2018 20:56:17.870 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
02-May-2018 20:56:17.870 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Ddatasource.jdbcUrl=jdbc:postgresql://pg:5432/ggal1701
02-May-2018 20:56:17.870 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Ddatasource.user=postgres
02-May-2018 20:56:17.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Ddatasource.password=postgres
02-May-2018 20:56:17.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djdk.tls.ephemeralDHKeySize=2048
02-May-2018 20:56:17.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.protocol.handler.pkgs=org.apache.catalina.webresources
02-May-2018 20:56:17.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dignore.endorsed.dirs=
02-May-2018 20:56:17.871 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.base=/usr/local/tomcat
02-May-2018 20:56:17.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Dcatalina.home=/usr/local/tomcat
02-May-2018 20:56:17.872 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -Djava.io.tmpdir=/usr/local/tomcat/temp
02-May-2018 20:56:17.872 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent Loaded APR based Apache Tomcat Native library 1.2.16 using APR version 1.5.2.
02-May-2018 20:56:17.872 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
02-May-2018 20:56:17.882 INFO [main] org.apache.catalina.core.AprLifecycleListener.initializeSSL OpenSSL successfully initialized (OpenSSL 1.1.0f 25 May 2017)
02-May-2018 20:56:18.001 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["http-apr-8080"]
02-May-2018 20:56:18.010 INFO [main] org.apache.coyote.AbstractProtocol.init Initializing ProtocolHandler ["ajp-apr-8009"]
02-May-2018 20:56:18.011 INFO [main] org.apache.catalina.startup.Catalina.load Initialization processed in 614 ms
02-May-2018 20:56:18.040 INFO [main] org.apache.catalina.core.StandardService.startInternal Starting service Catalina
02-May-2018 20:56:18.041 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.0.51
02-May-2018 20:56:18.066 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /usr/local/tomcat/webapps/ROOT.war
02-May-2018 20:56:21.589 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
20:56:21.802 [localhost-startStop-1] WARN es.enxenio.GGAL1701.ApplicationWebXml - No Spring profile configured, running with default configuracion
20:56:22.446 [localhost-startStop-1] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/logging.exception-conversion-word]
name [LOGGING_EXCEPTIONCONVERSIONWORD]. javax.naming.NameNotFoundException: Name [LOGGING_EXCEPTIONCONVERSIONWORD] is not bound in this Context. Unable to find [LOGGING_EXCEPTIONCONVERSIONWORD].
20:56:22.456 [localhost-startStop-1] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [LOGGING_EXCEPTIONCONVERSIONWORD]
20:56:22.456 [localhost-startStop-1] DEBUG org.springframework.jndi.JndiPropertySource - JNDI lookup for name [LOGGING_EXCEPTIONCONVERSIONWORD] threw NamingException with message: Name [LOGGING_EXCEPTIONCONVERSIONWORD] is not bound in this Context. Unable to find [LOGGING_EXCEPTIONCONVERSIONWORD].. Returning null.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.7.RELEASE)
2018-05-02 20:56:22.956 INFO 1 --- [ost-startStop-1] es.enxenio.GGAL1701.ApplicationWebXml : Starting ApplicationWebXml on c72e1d8684c7 with PID 1 (/usr/local/tomcat/webapps/ROOT/WEB-INF/classes started by root in /usr/local/tomcat)
2018-05-02 20:56:22.958 DEBUG 1 --- [ost-startStop-1] es.enxenio.GGAL1701.ApplicationWebXml : Running with Spring Boot v1.4.7.RELEASE, Spring v4.3.9.RELEASE
2018-05-02 20:56:22.959 INFO 1 --- [ost-startStop-1] es.enxenio.GGAL1701.ApplicationWebXml : The following profiles are active: prod
2018-05-02 20:56:23.096 DEBUG 1 --- [kground-preinit] org.jboss.logging : Logging Provider: org.jboss.logging.Slf4jLoggerProvider found via system property
2018-05-02 20:56:25.745 DEBUG 1 --- [ost-startStop-1] net.bull.javamelody : spring interceptor initialized
2018-05-02 20:56:25.757 DEBUG 1 --- [ost-startStop-1] net.bull.javamelody : spring interceptor initialized
2018-05-02 20:56:25.758 DEBUG 1 --- [ost-startStop-1] net.bull.javamelody : spring interceptor initialized
2018-05-02 20:56:27.019 INFO 1 --- [ost-startStop-1] e.enxenio.GGAL1701.config.WebConfigurer : Web application configuracion, using profiles: [prod]
2018-05-02 20:56:27.020 DEBUG 1 --- [ost-startStop-1] e.enxenio.GGAL1701.config.WebConfigurer : Registering Caching HTTP Headers Filter
2018-05-02 20:56:27.021 INFO 1 --- [ost-startStop-1] e.enxenio.GGAL1701.config.WebConfigurer : Web application fully configured
2018-05-02 20:56:27.056 WARN 1 --- [ost-startStop-1] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [es/enxenio/GGAL1701/config/DatabaseConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2018-05-02 20:56:27.062 WARN 1 --- [ost-startStop-1] o.s.boot.SpringApplication : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' available)
2018-05-02 20:56:27.198 ERROR 1 --- [ost-startStop-1] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method entityManagerFactory in es.enxenio.GGAL1701.config.DatabaseConfiguration required a bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' in your configuration.
02-May-2018 20:56:27.199 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:755)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:731)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [es/enxenio/GGAL1701/config/DatabaseConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
02-May-2018 20:56:27.202 SEVERE [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Error deploying web application archive /usr/local/tomcat/webapps/ROOT.war
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:759)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:731)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
02-May-2018 20:56:27.204 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /usr/local/tomcat/webapps/ROOT.war has finished in 9,137 ms
02-May-2018 20:56:27.212 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/docs
02-May-2018 20:56:27.267 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/docs has finished in 55 ms
02-May-2018 20:56:27.270 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/examples
02-May-2018 20:56:27.535 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/examples has finished in 265 ms
02-May-2018 20:56:27.535 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/host-manager
02-May-2018 20:56:27.566 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/host-manager has finished in 31 ms
02-May-2018 20:56:27.566 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /usr/local/tomcat/webapps/manager
02-May-2018 20:56:27.588 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /usr/local/tomcat/webapps/manager has finished in 22 ms
02-May-2018 20:56:27.593 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-apr-8080"]
02-May-2018 20:56:27.631 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-apr-8009"]
02-May-2018 20:56:27.651 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 9639 ms
You have two choices, both works correctly:
The first is to pass the values as JAVA_OPTS as follows (you are going through the parameters wrong):
docker run \
--network public \
--link pg \
--name tm \
-e JAVA_OPTS= \
"-Dspring.datasource.url=jdbc:postgresql://pg:5432/ggal1701
-Dspring.datasource.username=postgres \
-Dspring.datasource.password=postgres" \
-p 9000:8080 worker
The second is to pass the values as environment variables as follows (your mistake is the absence of quotes):
docker run \
--network public \
--link pg \
--name tm \
-e DATASOURCE_JDBC_URL="jdbc:postgresql://pg:5432/ggal1701" \
-e DB_USERNAME="postgres" \
-e DB_PASSWORD="postgres" \
-p 9000:8080 worker
Remember to specify these parameters in your configuration to use this second option. In the first one you don't have to configure anything directly.
As part of the devOps culture I never recommend hardcoding the settings and opting for the second option while it is intended for that purpose. They both have to work for you, and if you don't, you have some other mistake.
What you say about the hikariPool error is only a consequence of the datasource failure. Try one of these two ways and, in my professional opinion, opt for the second.
I leave you a good tutorial: Spring-boot tutorial
If your task is to pass jdbc url as a parameter during container startup there is not need to do it through DatabaseConfiguration. It can be done fairly simpler using placeholders in your configuration and environment variables in docker-run command.
Define placeholders in the configuration:
spring:
datasource:
url: ${JDBC_URL}
username: ${DATABASE_USERNAME}
password: ${DATABASE_PASSWORD}
And run the container like this:
docker run \
--network public \
--link pg \
--name tm \
-e JDBC_URL="jdbc:postgresql://pg:5432/ggal1701" \
-e DATABASE_USERNAME="postgres" \
-e DATABASE_PASSWORD="postgres" \
-p 9000:8080 worker
Note: docker link is deprecated functionality, you'd probably want to replace it.
Java properties should work according to the Spring Boot Externalized Configuration Docs. Might that be that you're not using the right name for the java properties?
From your production properties I see, for instance, that the property for the database URL is spring.datasource.url:
spring:
# Configuración de la BASE DE DATOS
datasource:
url: jdbc:postgresql://pg:5432/ggal1701
However you passing through the following Java Property:
-Ddatasource.jdbcUrl=jdbc:postgresql://pg:5432/ggal1701
I think instead you should use:
-Dspring.datasource.url=jdbc:postgresql://pg:5432/ggal1701
Another suggestion that always worked for me is to use environment variables instead of java properties. You can was them with equal simplicity to your Docker:
-e SPRING_DATASOURCE_URL=jdbc:postgresql://pg:5432/ggal1701