4

Last time I checked, when I did this:

FROM x:latest
ENV foo 'bar'

FROM y:latest
RUN echo "$foo"

then "echo $foo" was empty - is there a way to persist ENV vars across multi-stage builds?

  • One solution might be to write to an .env file, and then copy that file later. But from an .env file, I don't know how to create ENV declarations. –  May 23 '19 at 18:33
  • Can you try with foo=bar or foo='bar' ?? – Nicolás Alarcón Rapela May 23 '19 at 18:41
  • Nah that won't make a difference it should work either way, unless there are docs stating otherwise –  May 23 '19 at 18:47
  • can you review this https://unix.stackexchange.com/questions/241810/env-foo-bar-echo-foo-prints-nothing?noredirect=1&lq=1 – Nicolás Alarcón Rapela May 23 '19 at 18:52
  • The same question discussed, and a couple of workarounds offered. https://stackoverflow.com/questions/52904847/how-do-i-copy-variables-between-stages-of-multi-stage-docker-build – k-lusine Jun 06 '19 at 05:55

1 Answers1

4

A build argument might work for you in this case. The user won't be able to override it and it won't be available in the container but other than that I think it fits.

FROM alpine
ARG FOO
RUN echo first step FOO is $FOO

FROM alpine
ARG FOO
RUN echo second step FOO is $FOO

To build you need to pass --build-arg with a value.

$ docker build --build-arg FOO=bar .
Step 1/6 : FROM alpine
 ---> 055936d39205
Step 2/6 : ARG FOO
 ---> Running in 3f5f18206d06
Removing intermediate container 3f5f18206d06
 ---> 2b82e4b958f7
Step 3/6 : RUN echo first step FOO is $FOO
 ---> Running in c0256dfe286d
first step FOO is bar
Removing intermediate container c0256dfe286d
 ---> 79286b74611f
Step 4/6 : FROM alpine
 ---> 055936d39205
Step 5/6 : ARG FOO
 ---> Running in 9fc20546619f
Removing intermediate container 9fc20546619f
 ---> 30325962d73a
Step 6/6 : RUN echo second step FOO is $FOO
 ---> Running in a8906382909a
second step FOO is bar
Removing intermediate container a8906382909a
 ---> 521dbbfa398b
Successfully built 521dbbfa398b
kichik
  • 33,220
  • 7
  • 94
  • 114