0

In my docker file, I have an ARG that I need to further use in CMD. I try doing that via assigning that value to ENV first:

ARG COMPONENT
ENV EOMPONENT_NAME=${COMPONENT}

CMD ["/opt/apps/${COMPONENT_NAME}", "--seed"]

When I build and then run the image, I get an error stat /opt/apps/${COMPONENT_NAME}: no such file or directory: unknown. - the ENV variable doesn't get resolved.

If I use CMD without square brackets, it all works:

CMD /opt/apps/${COMPONENT_NAME} --seed

I understand the difference between using square braces or not - in the first case it's supposed to just run the command, in the second it wraps it with /bin/sh -c. But I still don't understand why the env variables don't get resolved when CMD is used with square braces.

Andrey
  • 20,487
  • 26
  • 108
  • 176
  • `why the env variables don't get resolved when CMD` What entity should expand the variable them? It is hard to answer a negative - it doesn't happen, because it doesn't happen, because nothing makes it happen - there is nothing that could expand a variable. – KamilCuk Aug 01 '23 at 16:39
  • Also see [Use environment variables in CMD](https://stackoverflow.com/questions/23071214/use-environment-variables-in-cmd) which is similar. – David Maze Aug 01 '23 at 22:34

1 Answers1

0

why the env variables don't get resolved when CMD is used with square braces.

Because nothing expands the string ${COMPONENT_NAME}, so it is not expanded.

I understand the difference between using square braces or not - in the first case it's supposed to just run the command, in the second it wraps it with /bin/sh -c

Exactly. And /bin/sh expands variable references by parsing the line according to shell syntax and running variable expansion (and word splitting expansion and filename expansion and other shell expansions) on the command. If you do not run a shell, or other program, nothing will happen.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • But where does the command run in the first case (with square braces)? Not in a shell? – Andrey Aug 01 '23 at 17:36
  • The command runs and only the command. `Not in a shell?` No. "Where" do you think the `/bin/sh -c` runs? It just runs, with the rootfs of the container. – KamilCuk Aug 01 '23 at 17:41