简体   繁体   中英

java.net.ConnectException: Connection refused (Connection refused): Docker + Spring boot

I have an external API that I want to consume, and I am using WebTarget for that purpose

private final String target_url = "http://localhost:3000/models";
WebTarget target = client.target(target_url);
GenericType<List<Model>> genericType = new GenericType<List<Model>>() {};
List<Model> modelList = target.request(MediaType.APPLICATION_JSON_VALUE).get(genericType);
server.port=3001

It is working fine without docker, I can access the external API at http://localhost:3000

But with Docker I cannot.

Dockerfile

FROM openjdk:8-jre-slim

COPY target/*.jar app.jar

ENTRYPOINT ["java","-jar","/app.jar"]

Both the containers are in same network

Command:

docker run --rm -p 3001:3001 --network external-api image-name:version

To run the external API, I am executing

docker run --rm -p 3000:3000 --network external-api external-api-image-name:version

I also executed ping between two containers

docker exec -ti 0d1e786b3f06 ping 19c5bb4ab4d5
PING 19c5bb4ab4d5 (172.27.0.2): 56 data bytes
64 bytes from 172.27.0.2: seq=0 ttl=64 time=0.232 ms
64 bytes from 172.27.0.2: seq=1 ttl=64 time=0.098 ms
64 bytes from 172.27.0.2: seq=2 ttl=64 time=0.169 ms
64 bytes from 172.27.0.2: seq=3 ttl=64 time=0.188 ms

ERROR:

java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_292]
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_292]
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_292]
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_292]
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_292]
    at java.net.Socket.connect(Socket.java:607) ~[na:1.8.0_292]
    at sun.net.NetworkClient.doConnect(NetworkClient.java:175) ~[na:1.8.0_292]
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463) ~[na:1.8.0_292]
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558) ~[na:1.8.0_292]
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:242) ~[na:1.8.0_292]
    .
    .
    .

The problem that your containers cannot access localhost in String target_url . You should override it in profiles or properties. For example you can move yours target_url to the class field and annotate it @Value(external.api.url) and in application.propeties add external.api.url=your_container_name:port/uri

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM