Search code examples
javadockerspring-bootkitematic

Spring boot inside docker container throws java.net.ConnectException: Connection refused (Connection refused)


The client application sends json data to server on localhost:8080 that is packaged and run as docker image. Servers work fine when manually sending json using Postman chrome app. The problem is with dockerized client that throws java.net.ConnectException: Connection refused (Connection refused) when trying to write json to HttpURLConnection using OutputStreamWriter. How to make it work?

Dockerfile:

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG JAR_FILE=target/client-0.0.1-SNAPSHOT.jar
COPY ${JAR_FILE} app.jar
EXPOSE 8088
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

Solution

  • Both clients should run on the same network. So create a network bridge MY_BRIDGE:

    docker network create MY_BRIDGE
    

    Attach both container to the bridge, when running them. Give the server container a name MY_SERVER:

    docker run --network MY_BRIDGE --name MY_SERVER MY_SERVER_IMAGE
    
    docker run --network MY_BRIDGE MY_CLIENT_IMAGE
    

    Your application code has to be changed from localhost:8080 to MY_SERVER:8080 prior to running the client container.

    See Docker Bridge Documentation