Debian Codegraph @

inst/doc/docker.Rmd

raw
1 ---
2 title: "Using renv with Docker"
3 output: rmarkdown::html_vignette
4 vignette: >
5 %\VignetteIndexEntry{Using renv with Docker}
6 %\VignetteEngine{knitr::rmarkdown}
7 %\VignetteEncoding{UTF-8}
8 ---
9
10 ```{r, include=FALSE}
11 knitr::opts_chunk$set(
12 collapse = TRUE,
13 comment = "#>",
14 eval = FALSE
15 )
16 ```
17
18 While renv can help capture the state of your R library at some point in time, there are still other aspects of the system that can influence the runtime behavior of your R application. In particular, the same R code can produce different results depending on:
19
20 - The operating system in use,
21 - The compiler flags used when R and packages are built,
22 - The LAPACK / BLAS system(s) in use,
23 - The versions of system libraries installed and in use,
24
25 and so on. [Docker](https://www.docker.com/) is a tool that can help solve this problem through the use of **containers**. Very roughly speaking, one can think of a container as a small, self-contained system within which different applications can be run. Using Docker, one can declaratively state how a container should be built, and then use that system to run applications. For more details, please see <https://solutions.posit.co/envs-pkgs/environments/docker/>.
26
27 Using Docker and renv together, one can then ensure that both the underlying system, alongside the required R packages, are fixed and constant for a particular application.
28
29 This vignette will assume you are already familiar with Docker; if you are not yet familiar with Docker, the [Docker Documentation](https://docs.docker.com/) provides a thorough introduction. To learn more about using Docker to manage R environments, visit [solutions.posit.co](https://solutions.posit.co/envs-pkgs/environments/docker/).
30
31 We focus here on the most common case: you already have an existing renv project and want to build a Docker image from it. We assume that your project already contains `renv.lock`, `.Rprofile`, `renv/activate.R`, and `renv/settings.json`.
32
33 The examples below use `<parent-image>` as a placeholder for the base image, which is assumed to provide R and the system libraries required by your project's packages. The [Rocker project](https://rocker-project.org/) provides widely-used R base images; for example, `rocker/r-ver:4.4` pins a specific R version. Using a version-tagged base image is recommended for reproducibility. See the [system dependencies](#system-dependencies) section for help identifying which system libraries your packages need.
34
35
36 ## Containerizing an existing renv project
37
38 A good default is to copy the renv metadata first, restore packages, and only then copy the rest of the repository:
39
40 ```dockerfile
41 FROM <parent-image>
42
43 # initialize application project directory
44 WORKDIR /project
45 RUN mkdir -p renv
46
47 # copy renv infrastructure
48 COPY renv.lock renv.lock
49 COPY .Rprofile .Rprofile
50 COPY renv/activate.R renv/activate.R
51 COPY renv/settings.json renv/settings.json
52
53 # restore R project library
54 RUN R -s -e "renv::restore()"
55
56 # copy application files into image
57 COPY . .
58 ```
59
60 You should also add a `.dockerignore` file to prevent the host's project library and other renv working directories from being copied into the build context:
61
62 ```
63 renv/*
64 !renv/activate.R
65 !renv/settings.json
66 ```
67
68 This excludes everything inside `renv/` except the two files the Dockerfile needs. The project library, sandbox, and other working directories are either rebuilt by `renv::restore()` inside the container or are host-specific, so they should not be copied into the image.
69
70 This is a good starting point for most projects. The image restore step uses the same project metadata that you already commit to version control, so the container can recreate the project library before the rest of the source tree is copied. Note that renv does not need to be pre-installed on the parent image: when R starts, it sources `.Rprofile`, which in turn sources `renv/activate.R`. The activate script automatically downloads and installs renv if it is not already available.
71
72 If you need to customize the library path, set `RENV_PATHS_LIBRARY` before calling `renv::restore()`:
73
74 ```dockerfile
75 ENV RENV_PATHS_LIBRARY=/renv/library
76 RUN R -s -e "renv::restore()"
77 ```
78
79
80 ## Caching package installs
81
82 If you rebuild the same image repeatedly, caching can make `renv::restore()` much faster. There are three common approaches.
83
84
85 ### Basic Docker layer cache
86
87 The Dockerfile above already uses Docker's normal layer cache. Because `renv::restore()` happens before `COPY . .`, changes to application code do not invalidate the restore layer. Docker only needs to run `renv::restore()` again when the copied renv files change.
88
89
90 ### Cache mounts
91
92 If you are using BuildKit, you can also mount a cache directory into the build. This allows `renv::restore()` to reuse previously cached packages even when the restore layer itself needs to be rebuilt.
93
94 ```dockerfile
95 # syntax=docker/dockerfile:1
96 FROM <parent-image>
97
98 # initialize application project directory
99 WORKDIR /project
100 RUN mkdir -p renv
101
102 # copy renv infrastructure
103 COPY renv.lock renv.lock
104 COPY .Rprofile .Rprofile
105 COPY renv/activate.R renv/activate.R
106 COPY renv/settings.json renv/settings.json
107
108 # set path to the renv package cache
109 ENV RENV_PATHS_CACHE=/renv/cache
110
111 # ensure packages are copied, not symlinked
112 ENV RENV_CONFIG_CACHE_SYMLINKS=FALSE
113
114 # restore with mounted cache
115 RUN --mount=type=cache,target=/renv/cache \
116 R -s -e "renv::restore()"
117
118 # copy application files into the image
119 COPY . .
120 ```
121
122 The `RENV_PATHS_CACHE` environment variable tells renv where to find its package cache. The `RUN --mount=type=cache` line tells BuildKit to make a persistent build cache available at that path for the duration of the `RUN` instruction, so `renv::restore()` can reuse previously downloaded packages; see Docker's [`RUN --mount` documentation](https://docs.docker.com/reference/dockerfile/#run---mount) and [cache mount guide](https://docs.docker.com/build/cache/optimize/).
123
124 Setting `RENV_CONFIG_CACHE_SYMLINKS=FALSE` is important here because the cache mount is not part of the final image. With symlinks enabled, renv could leave the project library pointing at packages in the mounted cache, and those symlinks would be broken once the build step finishes.
125
126 This cache only helps on the specific machine or builder that created it. It is useful for repeated local builds, but it will not usually carry over to a different machine or a fresh CI runner.
127
128
129 ### Bind-mounted host caches
130
131 If the host machine already has a populated renv cache, you can bind-mount that cache into the build and let `renv::restore()` reuse it. This is especially useful when the host cache is managed outside Docker.
132
133 The Dockerfile can mount a host-provided cache context into the renv cache path:
134
135 ```dockerfile
136 # syntax=docker/dockerfile:1
137 FROM <parent-image>
138
139 # initialize application project directory
140 WORKDIR /project
141 RUN mkdir -p renv
142
143 # copy renv infrastructure
144 COPY renv.lock renv.lock
145 COPY .Rprofile .Rprofile
146 COPY renv/activate.R renv/activate.R
147 COPY renv/settings.json renv/settings.json
148
149 # set path to the renv package cache
150 ENV RENV_PATHS_CACHE=/renv/cache
151
152 # ensure packages are copied, not symlinked
153 ENV RENV_CONFIG_CACHE_SYMLINKS=FALSE
154
155 # restore with mounted cache
156 RUN --mount=type=bind,from=renv-cache,source=.,target=/renv/cache,rw \
157 R -s -e "renv::restore()"
158
159 COPY . .
160 ```
161
162 The `RUN --mount=type=bind` line tells BuildKit to mount the named build context `renv-cache` at the renv cache path for that one `RUN` instruction, with temporary write access; see Docker's [`RUN --mount` documentation](https://docs.docker.com/reference/dockerfile/#run---mount) and [named contexts documentation](https://docs.docker.com/build/building/context/#named-contexts).
163
164 You can then provide that cache directory at build time with `docker buildx build`:
165
166 ```sh
167 docker buildx build \
168 --build-context renv-cache=.cache/renv \
169 -t <image-name> .
170 ```
171
172 This approach is most useful when `.cache/renv` has already been populated on the host, for example by running `renv::restore()` outside Docker.
173
174 Bind mounts are read-only by default, so the example uses `rw` to avoid write failures if `renv::restore()` needs to update the cache during the build. Even with `rw`, writes to the bind mount are only available for the duration of that `RUN` instruction and are discarded afterwards, so the host-provided cache context is not modified. This helps keep repeated builds reproducible, including when multiple builds run sequentially or in parallel.
175
176 `RENV_CONFIG_CACHE_SYMLINKS=FALSE` is needed here for the same reason as in the cache-mount example: the mounted cache is available during the build step, but it is not carried into the final image.
177
178 This is often the preferred approach on ephemeral hosts such as GitHub Actions runners, because the host-side cache directory can be restored with the CI platform's native cache support before the build starts. GitHub Actions and Azure DevOps both provide native cache features that work well for this: [GitHub Actions cache](https://docs.github.com/actions/concepts/workflows-and-actions/dependency-caching) and [Azure DevOps Cache task](https://learn.microsoft.com/azure/devops/pipelines/release/caching?view=azure-devops).
179
180
181 ## System dependencies
182
183 Many R packages require system libraries to compile (e.g. `libcurl`, `libxml2`). These need to be installed before `renv::restore()` runs. You can use [renv::sysreqs()] to compute the system packages required by your project:
184
185 ```r
186 renv::sysreqs(distro = "ubuntu:24.04", report = TRUE, collapse = TRUE)
187 ```
188
189 This reports the installation command needed for a given distribution, which you can then add to your Dockerfile before the restore step:
190
191 ```dockerfile
192 RUN apt-get update && apt-get install -y --no-install-recommends \
193 libcurl4-openssl-dev \
194 libxml2-dev \
195 && rm -rf /var/lib/apt/lists/*
196 ```
197
198
199 ## Multi-stage builds
200
201 For production images, a multi-stage build can separate the build environment (with compilers and development headers) from the final runtime image. This keeps the deployed image smaller by excluding tools that are only needed to compile packages. See Docker's [multi-stage build documentation](https://docs.docker.com/build/building/multi-stage/) for details.
202
203