How to use environmental variables to pass values to a R docker
The idea of having R docker able to get external values when running is quite interesting.
As an example, suppose you have a docker that performs x+1
and that you want to pass x
to the docker when running it.
The easiest way consist of forcing R
to read x
from an environmental variable, say X
and then pass X
to the docker with the --env
option.
Suppose you have a R docker build by the following dockerfile:
FROM rocker/r-ver:4.0.5
RUN mkdir /data
RUN mkdir /app
RUN chmod -R 755 /app
WORKDIR /app
ADD main.R .
CMD R -e "source('main.R')"
Where the script main.R
is:
x <- Sys.getenv("X")
y <- x+1
write(y, '/data/y.txt')
After building the docker with:
docker build -t mydocker .
You can run it with
sudo docker run --env X=99 --rm -v /data/:/data mydocker
You should see the value of y
, presumably 100, in the output file y.txt
If you see mistakes or want to suggest changes, please create an issue on the source repository.
For attribution, please cite this work as
Spano (2021, Oct. 3). andreaspano blog: Environmental variables in Rocker. Retrieved from https://andreaspano.github.io/posts/2021-10-03-environmental-variables-in-rocker/
BibTeX citation
@misc{spano2021environmental, author = {Spano, Andrea}, title = {andreaspano blog: Environmental variables in Rocker}, url = {https://andreaspano.github.io/posts/2021-10-03-environmental-variables-in-rocker/}, year = {2021} }