Pass arg to docker build

deathangel908

I want to pass a variable during build time and start the script with this argument on run. How do I do it?

Dockerfile

FROM alpine
ARG var
# ENV var=${var} # doesn't work
CMD ["echo", "${var}"]
# ENTRYPOINT ["echo", "$var"] # doesn't work
# ENTRYPOINT "echo" "$var" # doesn't work

Running:

docker run -t $(docker build  --build-arg  var=hello -q .) 

Produces:

$var
Stefano

Note: Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, CMD [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: CMD [ "sh", "-c", "echo $HOME" ]. When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.

In other words a correct Dockerfile would be:

FROM alpine
ARG var
ENV var $var
CMD echo $var

In order to build it correctly, you should run:

docker run -t $( docker build --build-arg=var=hello -q . ) 

src: https://docs.docker.com/engine/reference/builder/#cmd

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Docker build-arg and copy

Docker - Build Arg in Source File

Execute a host system command and pass the result as build arg in docker-compose

docker build with --build-arg with multiple arguments

Can't use ARG in docker multistage build

envsubst within docker using build-arg

docker multistage build fails with multiple --build-arg

Google Cloud Build Docker build-arg from file

docker build --build-arg loses value and expands to empty string

Nesting parameters in --build-arg of docker build command

In a Docker Build with the build-arg flag,values are not getting passed correctly

How to pass docker run command line arg to docker-compose?

Pass --net=host to docker build

Docker compose on ecr: ERROR: No such service: --build-arg

How to pass an ARG to a Dockerfile in a docker-compose.yml

Use an argument from docker-compose build --build-arg inside a Dockerfile

How to pass jenkins credentials into docker build command?

How to pass ENV variable to build process in Docker

Dockerfile pass environments on docker compose build

How to pass securely SSH Keys to Docker Build?

Gitlab CI pass environment variable to docker build

Pass ARG to ENTRYPOINT

Pass arg while importing

Possible to pass `docker build` flags via docker-compose?

Select ENV/ARG in Dockerfile depending on build ARG

Lua function with arg pass to another function with arg

Jenkinsfile not using full docker-compose command, losing build-arg

Can't build Docker multi-stage image using ARG in COPY instruction

How can I execute a shell command to populate a docker-compose build arg?