RSS Feed Subscribe to RSS Feed

 

Using Docker with a maven project

If you have a maven project, there are a plethora of ways to enable it to run within a docker container.

Many are covered in this stackoverflow posting, including

  • Running the mvn command from within the “docker run” command
  • Having the docker run command link to an image in a repository such as nexus
  • Using the docker-maven-plugin

But the one option that I have found easiest is to just add a Docker file.
For take this simple Spring Boot Hello World type project: https://github.com/sabram/boothello

Running it without Docker is simple:

    git clone https://github.com/sabram/boothello.git
    mvn package && java -jar target/boothello-0.0.1-SNAPSHOT.jar
    curl http://localhost:8080/

But running in Docker is also straightforward. You can just add a file called Dockerfile in root, with something like:

    FROM java:8
    EXPOSE 8080
    ADD /target/boothello-0.0.1-SNAPSHOT.jar boothello.jar
    ENTRYPOINT ["java","-jar","boothello.jar"]

(See src here. Note I haven’t yet tried to have the Dockerfile use the latest version, rather than hardcoding the version, 0.0.1)

Then, after building (mvn clean install, or however you usually do it) do:

    $ docker build -f Dockerfile -t boothello .
    $ docker run -p 8080:8080 -t boothello
    $ curl http://localhost:8080

You can also obviously adapt to use versioning, such as:

    $ docker build -f Dockerfile -t boothello:v1 .
    $ docker run -p 8080:8080 -t boothello:v1
    $ curl http://localhost:8080

And also adapt to have the port that the container exposes be different from the actual app. For example, we can leave the app running on port 8080 but have the container expose port 8081

    $ docker run -p 8081:8080 -t boothello:v1
    $ curl http://localhost:8081

Tags: , , , , ,

Leave a Reply