我有一个jar,如果提供的话,它可以处理命令行参数,或者打开一个shell:
$ java -cp incrementor.jar de.peer.shell.incrementor.Main 4
4 + 1 = 5
$ java -cp incrementor.jar de.peer.shell.incrementor.Main
4
4 + 1 = 5
exit
我想对这个jar进行docker化,以便可以以任何一种方式执行它。我的Dockerfile
是:
FROM openjdk:latest
COPY incrementor.jar /usr/src/incrementor.jar
???
我可以通过添加CMD java -cp /usr/src/incrementor.jar de.peer.shell.incrementor.Main 4
$ docker image build -t incrementor:hardcoded .
$ docker run incrementor:hardcoded
4 + 1 = 5
我可以通过添加CMD java -cp /usr/src/incrementor.jar de.peer.shell.incrementor.Main
$ docker image build -t incrementor:shell .
$ docker run -it incrementor:shell
4
4 + 1 = 5
exit
$ docker run -it incrementor:shell 5 # same result for skipping `-it`
docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"5\": executable file not found in $PATH": unknown.
ERRO[0002] error waiting for container: context canceled
而且我可以通过添加ENTRYPOINT ["java", "-cp", "/usr/src/incrementor.jar", "de.peer.shell.incrementor.Main"]
$ docker image build -t incrementor:cmdargs .
$ docker run incrementor:cmdargs 4
4 + 1 = 5
$ docker run incrementor:cmdargs
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at de.peer.shell.incrementor.Main.main(Main.java:13)
如何构建一个容器,使其既可以处理命令行参数又可以处理命令行参数?
答案 0 :(得分:1)
最后一个例子是正确的,您只需要为外壳添加-it
:
FROM openjdk:latest
COPY incrementor.jar /usr/src/incrementor.jar
ENTRYPOINT ["java", "-cp", "/usr/src/incrementor.jar", "de.peer.shell.incrementor.Main"]
然后
$ docker image build -t incrementor:both .
$ docker run incrementor:both 4
4 + 1 = 5
$ docker run -it incrementor:both
4
4 + 1 = 5
exit