javadockernanohttpd

Nanohttpd exits immediately when run in Docker container


I wrote a simple microservice in Java using nanohttpd for the HTTP server. I am able to run it from the jar file directly from the Windows 10 command prompt like this:

D:\Docker\JoeMicroserviceTest\src>java -jar JoeMicroserviceTest-1.0-SNAPSHOT.jar

The server starts fine and displays:

Server started, Hit Enter to stop.

I can then make HTTP requests against the server, and everything works great.

I then put it in a Docker image, and when I run it, the container starts, the nanohttpd server starts, then immediately stops. This is what I see:

Server started, Hit Enter to stop.

Server stopped.

There is pretty much no delay between the starting and stopping. And then of course my container exits because the server process stopped.

Here is my dockerfile:

FROM openjdk:8
COPY ./src/ /usr/src/JoeMicroserviceTest
WORKDIR /usr/src/JoeMicroserviceTest
CMD ["java","-jar","JoeMicroserviceTest-1.0-SNAPSHOT.jar"]
EXPOSE 8080

I build it like this:

docker build -t joe-microservice-test .

I run it like this:

docker run -p 8080:8080 joe-microservice-test

Why could this be happening?


Solution

  • Ok, I got this working by adding "-dit" to the run command. Here is the working run command:

    docker run -dit -p 8080:8080 joe-microservice-test
    

    Here's another question that helps explain why it's needed.