0

I'm trying to create a temporary folder and then set the path as an environment variable for use in later Dockerfile instructions:

FROM alpine

RUN export TEMPLATES_DIR=$(mktemp -d)
ENV TEMPLATES_DIR=$TEMPLATES_DIR

RUN echo $TEMPLATES_DIR

Above is what I've tried, any idea how I can achieve this?

0

1 Answer 1

2

Anything you run in a Dockerfile will be persisted forever in the resulting Docker image. As a general statement, you don't need to use environment variables to specify filesystem paths, and there's not much point in creating "temporary" paths. Just pick a path; it doesn't even need to be a "normal" Linux path since the container filesystem is isolated.

RUN mkdir /templates

It's common enough for programs to use environment variables for configuration (this is a key part of the "12-factor" design) and so you can set the environment variable to the fixed path too

ENV TEMPLATES_DIR=/templates

In the sequence you show, every RUN step creates a new container with a new shell, and so any environment variables you set in a RUN command get lost at the end of that step. You can't set a persistent environment variable in quite the way you're describing; Create dynamic environment variables at build time in Docker discusses this further.

If it's actually a temporary directory, and you're intending to clean it up, there are two more possibilities. One is to do all of the work you need inside a single RUN step that runs multiple commands. The environment variable won't outlive that RUN step, but it will be accessible within it.

RUN export TEMPLATES_DIR=$(mktemp -d) \
 && echo "$TEMPLATES_DIR" \
 && rm -rf "$TEMPLATES_DIR"

A second is to use a multi-stage build to do your "temporary" work in one image, but then copy the "permanent" parts of it out of that image into the final image you're actually shipping.

Sign up to request clarification or add additional context in comments.

2 Comments

the actual reason why I want to use a directory in /tmp is to avoid hassle with permissions. I want to use this dir for some assets which are generated during the installation
It's pretty common to run all the Dockerfile steps as root, which also avoids permission trouble. Setting up an alternate user is a good idea, but I wouldn't actually switch to it until the very end of the Dockerfile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.