DockerFile to run a java program
Another way...
- you have to use "java:8" as base image or install jdk on "ubuntu" image.
build the image
docker build -t imagename .
run it(mounting Helloworld.java to container)
docker run -it -v ~/system-path:/javafolder imagename
type these commands to execute inside container-
cd javafolder
javac HelloWorld.java
java HelloWorld
Explanation
From the Dockerfile reference.
There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect.
That is why the javac
command is not executed and starting your container results in no such file or directory
was found.
CMD
and ENTRYPOINT
are used for the tasks that shall be started once you execute the container (entrypoint level).
The main purpose of a CMD is to provide defaults for an executing container.
That applies to the line CMD java HelloWorld
, but not to CMD javac HelloWorld.java
which is more of a build step. That is what RUN
is for.
Solution
Change the second line to RUN javac HelloWorld.java
.
FROM scratch
RUN javac HelloWorld.java
CMD java HelloWorld
The resulting committed image [from line two] will be used for the next step in the Dockerfile.
Update
As Diyoda pointed out, make sure that the FROM
image supplies java.
You can save yourself by writing DockerFile as well, just have java image in your local image repo, compile and run your java program by passing your program to it, its very easy.
$ docker run java:alpine java -version
$ docker run --rm -v $PWD:/app -w /app java:alpine javac Main.java
$ docker run --rm -v $PWD:/app -w /app java:alpine java Main