Environmental variables in Rocker

How to use environmental variables to pass values to a R docker

Andrea Spano andreaspano.github.io
10-03-2021

Introduction

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.

Docker File

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')"

Main R script

Where the script main.R is:

x <- Sys.getenv("X")
y <- x+1
write(y, '/data/y.txt')

Run

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

Corrections

If you see mistakes or want to suggest changes, please create an issue on the source repository.

Citation

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}
}