92

I am able to pass the environment variables using the -e option. But i am not sure how to pass command line arguments to the jar in entrypoint using the docker run command.

Dockerfile

FROM openjdk
ADD . /dir
WORKDIR /dir
COPY ./test-1.0.1.jar /dir/test-1.0.1.jar
ENTRYPOINT java -jar /dir/test-1.0.1.jar

test.sh

#! /bin/bash -l

export AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id)
export AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key)

$value=7

docker run -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY  -i -t testjava  $value
jtlz2
  • 7,700
  • 9
  • 64
  • 114
nad87563
  • 3,672
  • 7
  • 32
  • 54

2 Answers2

116

Use ENTRYPOINT in its exec form

ENTRYPOINT ["java", "-jar", "/dir/test-1.0.1.jar"]

then when you run docker run -it testjava $value, $value will be "appended" after your entrypoint, just like java -jar /dir/test-1.0.1.jar $value

naimdjon
  • 3,162
  • 1
  • 20
  • 41
Siyu
  • 11,187
  • 4
  • 43
  • 55
  • 18
    ...and will override CMD from dockerfile (if it present) – Alex Torson May 09 '19 at 20:09
  • 5
    It does not work for me with the single quotes, `docker run myimage --build` complains about _--build: [npx,: not found_ (my dockerfile: `ENTRYPOINT ['npx', 'mycommand']`). Changing them to double quotes will work, i.e. `ENTRYPOINT ["npx", "mycommand"]` – zypA13510 Dec 03 '19 at 02:00
  • 2
    You have to use double quotes because it is actually using the JSON array syntax. – Lenormju Sep 06 '22 at 09:56
68

You should unleash the power of combination of ENTRYPOINT and CMD.

Put the beginning part of your command line, which is not expected to change, into ENTRYPOINT and the tail, which should be configurable, into CMD. Then you can simple append necessary arguments to your docker run command. Like this:

Dockerfile

FROM openjdk
ADD . /dir
WORKDIR /dir
COPY ./test-1.0.1.jar /dir/test-1.0.1.jar
ENTRYPOINT ["java", "-jar"]
CMD ["/dir/test-1.0.1.jar"]

Sh

# this will run default jar - /dir/test-1.0.1.jar
docker run testjava

# this will run overriden jar
docker run testjava /dir/blahblah.jar

This article gives a good explanation.

double-beep
  • 5,031
  • 17
  • 33
  • 41
grapes
  • 8,185
  • 1
  • 19
  • 31
  • 6
    Nice! but what if I want to pass more than one command line arguments? – xpt Oct 15 '21 at 16:27
  • 4
    The contents at linked URL were replaced with something different, apparently. – Anton Strogonoff Jul 21 '22 at 12:15
  • 1
    @xpt from `java --help` : `Arguments following [...] -jar [...] are passed as the arguments to main class`. So running `docker run testjava /dir/blahblah.jar -myarg1 -myarg2withvalue 123`. See also : `docker run --help` – Lenormju Sep 06 '22 at 09:59