How do I get my two docker containers to communicate with each other on Localhost?
I have separated out my project into a backend and a front-end. I am now trying to run both parts in separate docker containers however i get a connection refused. I tried running both on a docker network but it didn't seem to work.
Both my Dockerfiles look like
COPY ./build/libs/demo-0.0.1-SNAPSHOT.jar /usr/app/
WORKDIR /usr/app
RUN sh -c 'touch demo-0.0.1-SNAPSHOT.jar'
RUN apk add --update \
curl \
&& rm -rf /var/cache/apk/*
ENTRYPOINT ["java","-jar","demo-0.0.1-SNAPSHOT.jar"]
and the front end makes calls to the back end by
protected <T> ResponseEntity<T> getRequest(String path, Class<T> responseType) {
return restTemplate.getForEntity("http://localhost:8090/" + path, responseType);
}
but i get a
java.net.ConnectException: Connection refused (Connection refused)
I run both my container via:
docker run -p 8090:8090 -d repo/back-end
docker run -p 8080:8080 -d repo/front-end
In docker you can create your own network:
docker network create myNetwork
And run containers inside this network using --net
and --name
flags:
docker run -d -p 8000:8000 --net myNetwork --name backend backend-image
docker run -d -p 8001:8001 --net myNetwork frontend-image
Then you should be able to access backend using http://backend:8000
url from your frontend container.
Thanks both for the responses, i added a docker-compose.yml in frontend
version: '3'
services:
frontend:
build: .
ports:
- "8080:8080"
networks:
default:
external:
name: myNetwork
and in backend
version: '3'
services:
backend:
build: .
ports:
- "8090:8090"
networks:
default:
external:
name: myNetwork
and then changed my rest service to make calls to
private static final String prefix = "http://backend:8090/";
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.