Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build args does not pass in value to docker file

I want to build a docker image. And I run

docker build --build-arg project_file_name=account.jar -t account:1.0 .

The docker file looks like this (#1)

FROM anapsix/alpine-java:8u172b11_server-jre

ARG project_file_name

MAINTAINER jim
COPY src/${project_file_name} /home/${project_file_name}
CMD java -jar /home/${project_file_name}

If hardcode the variable, it will look like this (#2)

FROM anapsix/alpine-java:8u172b11_server-jre

MAINTAINER jim
enter code here
COPY src/account.jar /home/account.jar
CMD java -jar /home/account.jar

After I build the image with #1 and #2

Using #1, when I docker run, docker tell me it cannot find the specified jar file

Using #2, when I docker run, docker is able to execute the java jar file correctly.

To me both #1 and #2 are same. Just #1 use build-arg variable way and #2 is hardcoding the value. I believe the way I use build-args is incorrect. Can anyone guide me on this?

Regards

like image 408
Charles Brown Avatar asked Mar 29 '19 03:03

Charles Brown


People also ask

How do I pass args to Dockerfile build?

If you want to pass multiple build arguments with docker build command you have to pass each argument with separate — build-arg. docker build -t <image-name>:<tag> --build-arg <key1>=<value1> --build-arg <key2>=<value2> .

How do I set the default value of arg in Dockerfile?

The ARG directive in Dockerfile defines the parameter name and defines its default value. This default value can be overridden by the --build-arg <parameter name>=<value> in the build command docker build . The build parameters have the same effect as ENV , which is to set the environment variables.

How do I fix the docker build requires exactly one argument?

The most common reason for “Docker build Requires 1 Argument” error is when we try to build the image without providing sufficient arguments. Here, in the arguments, we need to provide the directory with the command. In order to solve this issue, we need to provide the correct file name with -f option.

How do I pass an environment variable in Dockerfile?

Use -e or --env value to set environment variables (default []). If you want to use multiple environments from the command line then before every environment variable use the -e flag. Note: Make sure put the container name after the environment variable, not before that.


1 Answers

A running container won’t have access to an ARG variable value., you'll need ENV variable for that. Though you can use ARG variable to set ENV variable. In your situation you can do

FROM anapsix/alpine-java:8u172b11_server-jre
ARG project_file_name
ENV PROJECT_FILE=${project_file_name}

MAINTAINER jim
COPY src/${project_file_name} /home/${project_file_name}
CMD java -jar /home/${PROJECT_FILE}

You can read more here

like image 149
Sukhpal Singh Avatar answered Oct 12 '22 13:10

Sukhpal Singh