59

I created a Docker image with java, and am copying the jar file into the image. My Dockerfile is :

FROM anapsix/alpine-java
MAINTAINER myNAME 
COPY testprj-1.0-SNAPSHOT.jar /home/testprj-1.0-SNAPSHOT.jar
RUN java -jar /home/testprj-1.0-SNAPSHOT.j

After executing following command :

docker build -t imageName.

In the console I see the output from the application and everything is fine. But when I stop the image, I don`t know how to run the image again ? When I execute the following command :

docker run -i -t imageName java -jar /home/testprj-1.0-SNAPSHOT.jar

The application runs again, but in my Dockerfile I have already written this command. How can I run the image without this command and have the application run automatically?

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92
Svetoslav Angelov
  • 667
  • 1
  • 6
  • 10

2 Answers2

107

There is a difference between images and containers.

  • Images will be built ONCE
  • You can start containers from Images

In your case:

Change your image:

FROM anapsix/alpine-java
MAINTAINER myNAME 
COPY testprj-1.0-SNAPSHOT.jar /home/testprj-1.0-SNAPSHOT.jar
CMD ["java","-jar","/home/testprj-1.0-SNAPSHOT.jar"]

Build your image:

docker build -t imageName .

Now invoke your program inside a container:

docker run --name myProgram imageName

Now restart your program by restarting the container:

docker restart myProgram

Your program changed? Rebuild the image!:

docker rmi imageName
docker build -t imageName .
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
blacklabelops
  • 4,708
  • 5
  • 25
  • 42
  • but then each time if we change the version of pom, we have to change the Dockerfile too, it could be easily forgotten – MK83 Feb 25 '22 at 14:09
11

This may not be quite what you asked, but if you just need to run a JAR (rather than that being just one part of a larger custom container) I like this approach of mapping a volume/folder to the JAR and running it using a standard upstream image:

docker run --rm -it -v /home/me/folderHoldingJar:/home:Z java:latest /bin/bash -c '/usr/bin/java -jar /home/theJarFile.jar'

There is even some additional args you can add if the JAR needs to display a GUI.

CrazyPyro
  • 3,257
  • 3
  • 30
  • 39
  • What if I want the application.jar already running when I start the container? Is it possible to create an image which has my .jar started so I don't have to wait for it to start when I spin up a container? For example if I start my app like `java -jar app.jar` it takes 20 seconds until it is ready to be accessible over localhost:8080. When I start it from a container I would like it to be ready without waiting 20 seconds. Is it possible? – Wlad Nov 05 '19 at 19:54
  • Thanks man, this is exactly what I wanted. – danieltalsky Mar 17 '21 at 20:32