Not able to access web app running inside docker container from local machine

2.1k Views Asked by At

I am using windows 10 enterprise version and i have tested docker hello world web app it works just fine.

Dockerfile

FROM adoptopenjdk/openjdk11:latest
WORKDIR /app
COPY ./ ./
EXPOSE 3000

CMD ["java", "-jar", "app.jar"]

These are the steps i followed:

  1. cd to directory where docker file is kept
  2. docker build .
  3. docker run -d -p 3000:3000 imageid

Now inside container i am able to access the app using curl command on port 3000 But from my local machine when i do http://localhost:3000 it says page is not working. Any help is appreciated ?

2

There are 2 best solutions below

0
On BEST ANSWER

After further debugging i found my server was only bound to localhost i.e. server connector was only listening on localhost and that's why it worked inside only container. I bound internal network interface(which resolved to an ip) to my server along with localhost(this is happening during server start-up), after this i was able to access the app from outside the container.

0
On

Here's one approach.

Let's say your Dockerfile for your webapp is (simplified for clarity):

FROM openjdk:8

COPY demo/target/application.jar .
CMD java -jar application.jar

Then you do a docker build to create the image:

docker build -t app:latest .

By default your webapp will run on port 8080 if you do a plain docker run:

docker run app

And as you mention, you can't access it from your local machine, but rather need to exec into the container:

docker exec -it app sh
curl localhost:8080

To access it from your local machine, you could modify your docker run to:

docker run -dp 82:8080 --name mywebapp app

What that does is it maps your host port 82 to the container's port 8080. Now you can access your webapp from your local browser at http://localhost:82 or via a local curl to the same.