Making a REST Call to Endpoint in Dockers

2019-07-12 02:21发布

问题:

I am building a Spring Boot application, which has a few different REST endpoints. It can be locally packaged and launched as a jar file successfully. When running locally, I can access its endpoints via "http://localhost:8080/endpoint?params..". I was tasked with now preparing this application to run off of Dockers. Still working on my local machine, I have created a Dockers container based off of the Java:8 image. In this container, I have been able to run my application from the .jar successfully. My issue is, I do not understand how to call to the REST endpoints inside the application, when the application is hosted off of Docker, since logically localhost:8080/endpoint is no longer responsive to the call.

Side information: My local computer is Windows, the Docker image is Ubuntu (eventually will be launched onto a Linux server).

UPDATE: Created a new image with the following Dockerfile:

FROM openjdk:8
MAINTAINER  My Name email@email.com
COPY . /usr/src/myapp
WORKDIR /usr/src/myapp
EXPOSE 8080
RUN javac Main.java
CMD ["java", "Main"]

Same issue, cannot access endpoint via http://localhost:8080/endpoint

Any help will be appreciated. Thank you!

回答1:

You need to publish the port (not EXPOSE it). Exposing a port is largely used for links and service contexts. In your example of just running a Docker container, you need to simply publish the port so it is available from the host. You do this with --publish or -p:

docker run -d --name myapp -p 8080:8080 myappimage

Then you can access the application at port 8080 on the host IP address (Docker on Windows and Docker on Mac run a proxy that should allow localhost:8080 to work).



回答2:

If your application is running inside of a Docker Container and you can access from inside this container using localhost:8080, then all you have to do is add the EXPOSE instruction in your DOCKERFILE (see Dockerfile expose option).

EXPOSE 8080

Then you probably will be able to access from the host machine (where Docker is installed and running) using the default IP from the docker0 network interface. Generally this IP is 172.17.0.X, where X is 2 for your first container, and so on (see docker default networking).

So try to access from outside of the docker using "http://172.17.0.2:8080/endpoint?params..". Also, if you want to allow external access (or access using localhost from the host machine) you should start your container mapping the port from the EXPOSE instruction by using -p parameter (see Mapping Exposed Incoming Ports).