7  Pinning the Environment with Docker

Though computational reproducibility seems more straight forward than replicating physical experiments, the complex and rapidly changing nature of computer environments makes being able to reproduce and extend such work a serious challenge.

Carl Boettiger, An Introduction to Docker for Reproducible Research (2015)

By the end of this chapter you will be able to write a Dockerfile that reaches L2, pinned environment, rather than one that merely looks reproducible. Its base will be named by an immutable digest, and its installer will fetch from a dated snapshot of the package repository. Its locale, time zone, and thread count will be declared in the recipe instead of inherited from whichever machine happens to run it.

NoteBefore you start

Reading time. About 55 minutes.

Prerequisites. Chapter 3, for the L0-L3 ladder and the capture-versus-validation vocabulary this chapter relies on throughout; Chapter 6, for the lockfile this chapter’s container restores inside itself and the L0-to-L1 step the container builds on. No R fluency beyond reading a short script is assumed; no Docker or systems-administration background is assumed, since the chapter builds the idea from first principles.

By the end of this chapter you will be able to answer:

  • Can you explain which determinants of a computational result a package lockfile leaves unpinned, and why a container is required to fix them?
  • Can you distinguish a Docker image from a container, and state the precise sense in which an image ‘runs the same everywhere it runs’?
  • Can you pin a base image by its immutable content digest, point its in-image installer at a dated repository snapshot, and say what each step secures?
  • Can you name the environment variables that govern locale, time zone, and thread determinism, and predict a concrete failure that each one prevents?
  • Can you select a Rocker profile appropriate to a given research archetype, and state honestly which rung of the reproducibility ladder a given image reaches and which it does not?

Outline.

  • Where this sits on the stack: the layers a container pins.
  • Orientation: a lockfile that restored and still computed a different number.
  • The analyst’s contribution: three judgments no tool automates.
  • What the lockfile leaves standing: the operating system, the system libraries, the R runtime.
  • Images and containers: the vocabulary, and the Rocker project.
  • Making the image itself reproducible: pinning by digest and by dated snapshot.
  • Apple Silicon and multi-architecture images: why a digest needs a fixed platform.
  • Environment-variable determinism: locale, time zone, thread count.
  • Profiles as base images, and a first look at the two-layer team model.
  • Worked example: one project walked from L1 to L2.
  • The cohort, continued: what the compendium’s own Dockerfile would still need.

You restore the same renv.lock on two laptops that run the same R release, and three things go wrong. In case (a), on one laptop the restore stops because a package cannot find a system library to compile against. In case (b), a regression coefficient differs in its sixth decimal place. In case (c), a bootstrap interval differs although the seed and code are identical, and one laptop’s project .Rprofile calls RNGkind(sample.kind = 'Rounding'). For each, name the determinant layer of Chapter 3 and say what closes it, drawing on Chapter 2 and Chapter 6.

The three failures after restoring one lockfile on two laptops sit in three different layers. Case (a) is the operating-system and system-library layer. A lockfile does not pin the system libraries that packages link against (Chapter 6), so this layer is closed only at L2, by a pinned environment. Case (b) is the numerical-library layer, the BLAS and LAPACK. No rung guarantees it (Chapter 3); fixing the thread count narrows it, and a stated tolerance absorbs what remains. Case (c) is session configuration. The .Rprofile overrides the default sampler with Rounding, the sampler R used before 3.6.0 (Chapter 2). An override is fixed only by an explicit RNGkind() call in the analysis code, not by the lockfile.

7.1 Where this sits on the stack

This chapter captures, for the first time in the book, the two layers beneath the packages. These are the operating system with its system libraries, and the R runtime itself. Figure 7.1 marks both as captured on the shared determinant stack of Chapter 3. The chapter captures nothing above those two layers. A container that pins the operating system and the R version still restores whatever the lockfile says about packages, which is the layer Chapter 6 already captures.

plot_determinant_stack(
  captures = c('Operating system, system libraries', 'R runtime'),
  title = 'Containers capture the operating system and the R runtime')
A horizontal bar chart of the nine-layer determinant stack, hardware at the bottom and intrinsic non-determinism at the top, each bar colored by, and labeled with, the rung that secures it across the book. This chapter captures Operating system, system libraries, R runtime; those layers are drawn at full color, labeled as captured or validated here, and, where validated, with a heavy outline. The remaining 7 layers are shown faded, for context, as secured elsewhere in the book. From the base, the rungs are: Hardware, unpinned by any rung; Numerical libraries (BLAS, LAPACK), unpinned by any rung; Operating system, system libraries, L2 pinned environment; R runtime, L2 pinned environment; Package versions, L1 pinned packages; Session configuration, L2 partially pinned; Analysis code, L0 locatable; Input data, L0 locatable; Intrinsic non-determinism, unpinned by any rung.
Figure 7.1: The determinant stack of Chapter 3, with the operating system and system libraries, and the R runtime, marked as captured by this chapter. These are the two layers a lockfile cannot reach, because neither is an R package; pinning them is the L1-to-L2 step this chapter teaches.

7.2 Orientation

Consider an epidemiologist who has done everything the previous chapter asked. Her cohort analysis is under version control, and every R package it uses is fixed to an exact version in a lockfile. She has reached L1, pinned packages, and she is entitled to some confidence. She sends the project to a collaborator, who runs renv::restore() and watches it fail. One of her packages links against the geospatial library GDAL, which is present on her machine and absent on his, and the package will not install without it. On a third machine the restore succeeds, but the analysis returns a subtly different figure, because that machine runs an older release of R in which a numerical default differs. The lockfile did its job perfectly.

The lockfile pins the R packages and nothing beneath them. It says nothing about the operating system, the system libraries such as GDAL or libxml2 that many packages link against, or the R interpreter itself. As Ushey observed in documenting renv, the tool records the packages an analysis used, not the platform it ran on (Ushey & Wickham, 2026). A lockfile restored under a different R version, or on an operating system missing a required system library, may fail to install or, more insidiously, may install and behave differently. This is the gap the present chapter closes. Its subject is the container, the technology that fixes the operating system, the system libraries, and the runtime, and so carries an analysis from L1 to L2, pinned environment.

We shall build the container from first principles, assuming no prior contact with it. The reason is that the health scientist who most needs reproducibility is rarely the one with a systems-administration background. We begin with what a container is, and proceed to the Rocker project that supplies R-specific containers. We then take up the two refinements that make a container itself reproducible rather than merely convenient, and the complication that multi-architecture images bring to a recent Mac. The environment variables that govern determinism follow. We close with the profiles and the team model, then work one project from L1 to L2 and check this book’s own compendium.

The epidemiologist’s lockfile restored cleanly on a third machine but produced a subtly different number. Her collaborator’s restore, on a second machine, failed outright. Name the determinant responsible for each failure, and say why the lockfile pinned neither.

The collaborator’s restore failed because a package linked against GDAL. GDAL is a system library the lockfile cannot name, because it is not an R package. The third machine’s different number came from an older R release in which a numerical default differed; the lockfile pins package versions, not the R version they run under. Both failures sit beneath the package layer, on the system-library layer and the R-runtime layer, which is the gap a container closes.

7.3 The analyst’s contribution

A container is a tool, and like every tool in this book it automates the mechanical part of the work and leaves the judgment to the analyst. Three decisions belong to the analyst and to no script.

  1. The choice of base environment must match the archetype, not the maximum. A container can carry anything, and it is tempting to reach for the largest base image that surely contains whatever one might need. That instinct is wrong. A manuscript archetype needs a base carrying a LaTeX toolchain; an R-package archetype needs only R and the check tools; a simulation archetype may want more cores than it wants software. Provisioning far above the need inflates the image, slows every rebuild, and obscures what the analysis actually depends on. The analyst chooses the smallest base that carries the real requirement.

  2. How far to pin decides whether the reproducibility claim is honest. Consider a container built on a mutable tag such as latest, which installs whatever the package repository serves on the day of the build. Such a container looks reproducible and is not. Two builds from the same recipe on different days produce different images. Fixing this costs a little effort now, in pinning the base by digest and the installer by date, and the analyst must decide to spend it. The chapter will argue that the effort is the difference between claiming L2 and reaching it.

  3. The environment variables that govern determinism are the analyst’s to set. A container inherits a locale, a time zone, and a default thread count. These silently shape sorting, date arithmetic, and the last bits of a floating point sum. No tool infers what the analysis needs; the analyst declares it, in a few lines that a later reader can inspect and trust.

NoteThe vocabulary of this chapter
  • Image. A frozen, read-only filesystem together with metadata, bundling an operating system, R, a set of packages, and configuration. It is analogous to a snapshot of a fully installed computer, packaged so it can be shipped.
  • Container. A running instance of an image. One image can start many containers; each begins from the same frozen filesystem.
  • Layer. Each instruction in an image’s recipe produces one filesystem layer. An image is the stack of its layers, and identical layers are shared and cached across images.
  • Base image. The starting image a recipe builds on, named on the FROM line. Here, a Rocker image providing a fixed R version on a fixed operating system.
  • Tag and digest. A tag, such as rocker/tidyverse:4.4.0, is a human-readable pointer that may later be repointed. A digest, @sha256:..., is an immutable hash of the content it names, and the same digest always denotes the same content. For a multi-architecture image that content is an index listing one image per platform, so a digest fixes one filesystem only together with a fixed platform, here --platform linux/amd64.
  • Rocker. The community project that publishes the standard R Docker images.
  • Dated snapshot. A frozen view of a package repository on a particular day, so that installing ‘the current version’ resolves to the same version on every build.
  • Profile. The base-image bundle a project is built from, such as minimal, tidyverse, rstudio, or publishing. It selects the FROM image.

A junior analyst asks why the base image is not simply ‘the biggest one available’, since a bigger image can only contain more of what might be needed. Using the first analyst judgment of this section, explain what is wrong with that reasoning.

The choice of base must match the archetype, not the maximum. A bigger image is not free. It inflates the image, slows every rebuild, and, more importantly, obscures what the analysis actually depends on, because anything the base happens to carry no longer shows up as a declared dependency in the lockfile. An R-package archetype that builds on a publishing base, for instance, could pass its checks while silently depending on a LaTeX toolchain its own declared dependencies never mention. The analyst chooses the smallest base that carries the real requirement.

7.4 What the lockfile leaves standing

The boundary of what a lockfile fixes is the whole motivation for the container. A lockfile records, for every R package the analysis code uses, the exact version and the repository it came from, and renv::restore() reinstalls that precise set (Ushey & Wickham, 2026). That is the L0-to-L1 transition, and it is genuine progress. Beneath the packages, however, sits a stack of determinants the lockfile never touches.

Three of these matter most. The first is the operating system, which supplies the C library and the conventions for locale and sorting against which every package was compiled. The second is the layer of system libraries, the compiled non-R software that packages link against: GDAL for spatial data, libxml2 for XML parsing, the numerical libraries that implement linear algebra. A package that needs GDAL will not install on a machine that lacks it, and the lockfile cannot supply it, because GDAL is not an R package. The third is the R interpreter itself. A lockfile pins the packages but not the R version: its R block records the version, and nothing in it can install that version. As we saw in the introduction, a change between R releases can alter a result silently: the sample() default that changed in R 3.6.0, the stringsAsFactors default that flipped in R 4.0.0. Restore the same lockfile under a different R, and the packages match while their behavior does not.

renv is therefore necessary and, by itself, insufficient. It closes the package layer cleanly and leaves the three layers beneath it exposed. Fixing those takes a tool that packages the whole computer the packages ran on, which is the container.

Name the three determinants beneath the package layer that a lockfile cannot pin, and say, for each, why it is not an R package and so cannot appear in a lockfile.

The operating system supplies the C library and the locale and sorting conventions every package was compiled against, and it is not installed by install.packages(). The system libraries, such as GDAL or libxml2, are compiled non-R software that packages link against but do not bundle, so renv has nothing to record about them. The R interpreter itself is the program the lockfile’s install.packages() calls run inside, not a package those calls install. Its version is recorded in the lockfile’s R block, but the lockfile cannot install it. All three need something beneath the package manager, which is the container’s job.

7.5 Images and containers

The idea of the container is straightforward, and it is easiest to grasp through the distinction between an image and a container. The two are as different as a recipe from a meal, or a class from an object.

An image is a frozen filesystem plus metadata. It is, quite literally, a snapshot of a fully installed computer: it holds an operating system, the system libraries, a particular R, a particular set of R packages, and the configuration that ties them together. All of this is captured as a single read-only artifact. The image does not run. It is inert, like a disk image or a virtual-machine template, waiting to be started.

A container is what one gets by starting an image. It is a running instance. The frozen filesystem is made live, and a process begins inside it. That process sees exactly the operating system and libraries the image froze, regardless of what the host machine outside the container happens to have. One image can start many containers, each an independent running copy that begins from the same frozen state. When a container exits, any change it made to its own filesystem is ordinarily discarded, and the next container starts again from the pristine image. The image is the durable, shippable thing; the container is the ephemeral, running thing.

Images are built in layers, which explains both the speed of the tool and the way we shall pin it. An image is built from a recipe, the Dockerfile, whose instructions execute in order, and each instruction adds one layer to a stack. A layer that installs the operating system sits at the bottom; a layer that installs R sits on top of it; a layer that installs packages sits on top of that. Because layers are content-addressed and cached, an unchanged lower layer is never rebuilt, and two images that share a base share its layers on disk. This is why building a second project from the same base is fast, and why, later, we shall be careful about which layer a given change invalidates.

The property that earns the container its place in this book is often summarized as ‘it runs the same everywhere it runs’. The claim is precise, and the repetition of ‘runs’ is deliberate. Wherever a container runtime is present, the same image starts a container with the same operating system, the same system libraries, and the same R. A result computed inside it therefore does not depend on the host. The qualification is that the container must actually run: the guarantee holds across every machine with a compatible runtime, and it is silent about machines that have none. This is a real boundary, and we return to it, and to the runtimes that widen it, in Chapter 8. For present purposes the container gives us what the lockfile could not: a fixed operating system, fixed system libraries, and a fixed R, traveling together as one artifact.

A colleague says, ‘I deleted a file inside the container by accident, so I restarted it and the file was back. Docker must have a recovery feature.’ What is actually happening, in the vocabulary of this section?

There is no recovery feature. A container is a running instance of a read-only image, and changes a container makes to its filesystem are ordinarily discarded when it stops. Restarting produces a fresh container that begins again from the pristine image, in which the file was never deleted. The image is durable and the container is ephemeral. This is the same property that makes a container reproducible: every run starts from the identical frozen state. It also means that anything one wants to keep, such as edited source or output, must live outside the container, on a host directory made visible inside it.

7.6 The Rocker project

A Dockerfile could, in principle, begin from a bare operating system and install R by hand. Almost no one does, because the R community maintains a set of ready base images that have become the standard starting point. This is the Rocker project. Boettiger introduced Docker to the reproducible-research audience and argued that a container is the natural unit for shipping a computational environment (Boettiger, 2015). Boettiger and Eddelbuettel then built and documented the Rocker images themselves, a family of R-specific base images maintained in step with R releases (Boettiger & Eddelbuettel, 2017). The fuller account, including the tooling that has grown around the images, is given by Nüst and colleagues in their survey of what they call the Rockerverse (Nüst, Eddelbuettel, et al., 2020).

The practical value of Rocker is that it supplies, for each R version, a tested base image with R already installed on a known operating system. The analyst’s recipe can then build on that shared foundation. The images form a small hierarchy. At the bottom sits rocker/r-ver, R on Ubuntu and little else. Above it, rocker/rstudio adds the RStudio Server development environment. rocker/tidyverse builds on rocker/rstudio, adding the tidyverse packages and the pandoc document converter, so it carries RStudio Server as well and is the larger of the two. And rocker/verse adds a LaTeX toolchain for rendering manuscripts to PDF. Each higher image is built on the one below, so they share layers, and each fixes a larger environment than the last. We shall meet these again as the profiles.

Starting a Dockerfile from a bare operating-system image and installing R by hand is possible. Explain why almost no one does, and what is lost in reproducibility terms if two analysts each hand-roll their own R installation rather than build on the same Rocker base.

A hand-rolled install recreates work the Rocker project has already done, tested, and kept in step with R releases, and is slower to build because it shares no cached layers with any other project. More to the point for reproducibility, two analysts who each write their own installation steps are two independent sources of small decisions. Examples are which compiler flags or which locale packages get installed. A shared Rocker base fixes those decisions identically for everyone who builds on it. Building on the same base image turns those into one decision made once, by the Rocker maintainers, rather than many decisions made silently and differently by each analyst.

7.7 Making the image itself reproducible

A container is reproducible only if the recipe that builds it is, and the naive recipe is not. Two refinements separate a container that merely runs today from one that will rebuild to the same image next year. Nüst and colleagues, in their ten simple rules for writing Dockerfiles for reproducible data science (Nüst, Sochat, et al., 2020), argue for pinning software versions explicitly. They also argue for naming version-specific image tags rather than :latest. At the same time they caution that even a version-specific tag is not a guarantee against change, since the maintainer can still rebuild and repoint it. (Inspected: the published rules recommend version tags, not cryptographic digests, and do not discuss dated package-repository snapshots.) This chapter takes that caution one step further than their rules do, with two refinements that do the most work here:

The first refinement pins the base image by its digest rather than by a tag. A tag such as rocker/tidyverse:4.4.0 is a mutable pointer. It names an image today, but the maintainers may rebuild and repoint it tomorrow, for instance to patch a security flaw in the operating system. A recipe that named the tag would then build on different bytes, without any change to the recipe itself. A digest is an immutable hash of the exact image content, so that

FROM rocker/tidyverse@sha256:1c2f...e8a9

names not ‘whatever 4.4.0 points to’ but one specific piece of content that the digest will denote forever. For the Rocker images this chapter uses, that content is an image index, a short table with one image per CPU architecture, from which a build receives the entry matching the platform it requests. A digest therefore fixes one filesystem only together with a fixed platform, so this book pins the index digest and always builds with --platform linux/amd64. The section on Apple Silicon below explains why that platform, and the alternative of pinning the platform-specific digest.

Figure 7.2 follows one unchanged recipe across a year to show what the difference costs. The recipe is not edited at any point in either row; the only thing that varies is whether its FROM line names the tag or the digest. (The digest strings shown here and in the figure, such as sha256:1c2f...e8a9 and sha256:6f05..., are truncated for display and illustrative only. A digest copied for actual use must be the full 64-character hash, such as the one the showcase Dockerfile below carries.) Nothing in the upper row is an error or a misconfiguration on the maintainer’s part. Repointing a tag to patch a security flaw is the correct thing for them to do, which is exactly why a tag cannot carry a reproducibility claim.

library(ggplot2)
library(tibble)

spans <- tibble(
  row = c('FROM rocker/r-ver:4.4.0',
          'FROM rocker/r-ver:4.4.0',
          'FROM rocker/r-ver:4.4.0',
          'FROM rocker/r-ver@sha256:6f05...'),
  xmin = c(0, 3.5, 8.5, 0),
  xmax = c(3.5, 8.5, 12, 12),
  build = c('build 1', 'build 2', 'build 3', 'build 1')
)
spans$row <- factor(spans$row,
                    levels = c('FROM rocker/r-ver@sha256:6f05...',
                               'FROM rocker/r-ver:4.4.0'))

ggplot(spans) +
  geom_rect(aes(xmin = xmin, xmax = xmax,
                ymin = as.numeric(row) - 0.26,
                ymax = as.numeric(row) + 0.26,
                fill = build),
            color = 'white', linewidth = 1.4) +
  scale_fill_manual(values = c('build 1' = '#14746f',
                               'build 2' = '#7fb1ad',
                               'build 3' = '#c9e2df'),
                    guide = 'none') +
  scale_y_continuous(breaks = 1:2,
                     labels = levels(spans$row),
                     limits = c(0.45, 2.95)) +
  scale_x_continuous(breaks = c(0, 3.5, 8.5, 12),
                     labels = c('Jan', 'Apr', 'Sep', 'Dec')) +
  annotate('text', x = 3.5, y = 2.42, label = 'maintainer\nrebuild',
           size = 2.6, lineheight = 0.95, color = 'grey25') +
  annotate('text', x = 8.5, y = 2.42, label = 'maintainer\nrebuild',
           size = 2.6, lineheight = 0.95, color = 'grey25') +
  annotate('text', x = 12.15, y = 2, hjust = 0,
           label = 'three environments\nfrom one recipe',
           size = 2.7, lineheight = 0.95, color = '#a33') +
  annotate('text', x = 12.15, y = 1, hjust = 0,
           label = 'one environment,\nalways',
           size = 2.7, lineheight = 0.95, color = 'grey25') +
  coord_cartesian(xlim = c(0, 16.6), clip = 'off') +
  labs(x = NULL, y = NULL) +
  theme_minimal(base_size = 9.5) +
  theme(
    panel.grid.major.y = element_blank(),
    panel.grid.minor = element_blank(),
    axis.text.y = element_text(family = 'mono', size = 8, hjust = 1)
  )
Two horizontal timelines running from January to December. The upper timeline, labeled FROM rocker/r-ver colon 4.4.0, is divided into three differently colored segments broken at April and September, marked as maintainer rebuilds, and annotated three environments from one recipe. The lower timeline, labeled FROM rocker/r-ver at sha256, is a single unbroken segment of one color across the whole year, annotated one environment, always.
Figure 7.2: One unchanged recipe built repeatedly over a year, under a tag and under a digest. The upper row builds on whatever the tag currently points at, so a maintainer rebuild in April and another in September silently change the ground the analysis stands on, giving three different environments from identical text. The lower row names a digest, builds for one fixed platform, and receives the same bytes at every build. The maintainer rebuilds are ordinary maintenance, not mistakes: the point is that a mutable pointer cannot carry an immutable claim.

The second refinement concerns what happens inside the image when it installs packages. An installer pointed at a live package repository resolves ‘the current version’ to whatever is current on the day of the build. An image built in March and an image built in June from the same recipe therefore carry different packages. The remedy is to point the in-image installer at a dated snapshot of the repository, a frozen view of the repository as it stood on a chosen day. With the snapshot fixed, a request for ‘the current version’ resolves to the same version on every build. In sum, the digest fixes the ground the image is built on. The lockfile, restored inside the image, fixes which package versions are installed onto it. The dated snapshot fixes where those packages are fetched from, and what any install that names no version resolves to.

A small Dockerfile with both refinements in place, and with the environment variables of the next section, follows. It is shown as static text, but we tested it. On 2026-10-11 we built it with docker build --platform linux/amd64 against a lockfile written by renv 1.2.3 that pins one package, jsonlite 2.0.0. The lockfile’s recorded R version was set to 4.4.0 to match the image, and the built image reported jsonlite 2.0.0 and renv 1.2.3. The digest is the one the rocker/r-ver:4.4.0 tag resolved to on that date. A reader adapting the recipe should look the digest up afresh, as Exercise 1 shows, rather than copy one from a book.

# rocker/r-ver:4.4.0 is built on Ubuntu 22.04 (jammy), so the
# binary snapshot below must name jammy. Digest as of 2026-10-11.
FROM rocker/r-ver:4.4.0@sha256:73adabf378930f8744f56bac1fe5e99870532eb4ced1a15075991bac909d21f3

ARG PPM_SNAPSHOT=https://packagemanager.posit.co/cran/__linux__/jammy/2026-06-27
ARG RENV_VERSION=1.2.3

LABEL org.opencontainers.image.base.name="docker.io/rocker/r-ver:4.4.0" \
      org.opencontainers.image.base.digest="sha256:73adabf378930f8744f56bac1fe5e99870532eb4ced1a15075991bac909d21f3" \
      cran.snapshot="2026-06-27"

ENV LANG=en_US.UTF-8 \
    LC_ALL=en_US.UTF-8 \
    TZ=UTC \
    OMP_NUM_THREADS=1 \
    OPENBLAS_NUM_THREADS=1 \
    RENV_CONFIG_REPOS_OVERRIDE=${PPM_SNAPSHOT}

# Later lines win, so this replaces Rocker's own snapshot date.
RUN echo "options(repos = c(CRAN = '${PPM_SNAPSHOT}'))" \
      >> /usr/local/lib/R/etc/Rprofile.site

WORKDIR /project
COPY renv.lock renv.lock

RUN Rscript -e "install.packages('renv')" \
 && Rscript -e "stopifnot(packageVersion('renv') == '${RENV_VERSION}')"

RUN Rscript -e "renv::restore(library = .libPaths()[1], prompt = FALSE)"

Several lines guard against failures that are easy to miss.

  • The base and the binary URL must agree. Rocker builds rocker/r-ver:4.4.0 FROM ubuntu:jammy, that is, Ubuntu 22.04, as its published Dockerfile for the release shows. Posit Package Manager serves Linux binaries compiled for a named distribution release, so the snapshot URL must say jammy. A URL naming a newer release, such as noble (24.04), would install binaries built against a different set of system libraries.
  • WORKDIR gives the project a directory of its own. Without it the build runs in /, the root of the file system, which renv would then treat as the project. That directory contains the home directory, and renv::init() refuses to initialize a project in that position. A dedicated directory avoids the problem and keeps renv’s files out of the root.
  • renv is installed at the version the lockfile records. The lockfile names the renv that wrote it, here 1.2.3. On the snapshot date that was the current release, so a plain install.packages('renv') fetches it, and the stopifnot() line turns any mismatch into a failed build. Passing --build-arg RENV_VERSION=1.2.2 makes the build stop at that line with packageVersion("renv") == "1.2.2" is not TRUE, which is how we confirmed the check can fail.
  • The snapshot governs the restore only because RENV_CONFIG_REPOS_OVERRIDE says so. By default renv::restore() ignores the session’s repository option and downloads from the repositories recorded in the lockfile. We confirmed both directions by building variants. With the override removed and a different date in Rprofile.site, the restore still fetched from the lockfile’s date. With the override set and a different date written into the lockfile, the restore fetched from the image’s snapshot, as jammy binaries.
  • library = .libPaths()[1] installs the restored packages into the image’s site library, so every R session in the container sees them without activating a project.

The build prints a warning from renv that curl does not appear to be installed and that downloads will fail. In this image the warning is harmless: the downloads go through R’s built-in libcurl support, as the completed restore shows.

The snapshot does not choose the versions of the packages in the lockfile; the lockfile does, and a recorded version older than the one current on the snapshot date is sought in the repository’s archive. What the snapshot fixes is the source of every download, the binary build that matches the image’s Ubuntu release, and the version of anything installed without a lockfile entry. Here that means renv itself, and any later install.packages() call made inside the running container. Rocker’s own image already points R at a dated snapshot, fixed for each R version at the last day that version was current (2024-06-13 for 4.4.0), which is why the echo line appends rather than replaces: the later setting wins.

The container and the lockfile divide the labor. The FROM line fixes the operating system, the system libraries, and the R; the snapshot fixes where packages come from; the COPY renv.lock and renv::restore() fix the exact package versions inside that environment. Neither the container nor the lockfile alone is enough. A container without a lockfile fixes the environment but not which package versions live in it; a lockfile without a container fixes the packages but not the platform. An L2 analysis uses both. The honest reading of an image, then, is that it reaches L2 only when the base is pinned by digest, the snapshot is dated, and a lockfile is restored inside it.

TipVerification

See the pinning actually hold by building the image twice and confirming the two builds carry the same content: the same operating system and the same R and package versions. This can be checked, for example, by comparing renv::status() and the installed apt and R package versions across the two builds. Do not test this by comparing the two image digests. Docker digests are not reproducible across rebuilds by default, because per-layer timestamps and file modification times differ, so two builds of a correctly pinned recipe carry different digests. Bit-identical digests require reproducible-build tooling, such as SOURCE_DATE_EPOCH and the BuildKit rewrite-timestamp option, which is a separate concern from whether the content is pinned. Make the check able to fail: replace the digest with a mutable tag and the snapshot with a live repository, rebuild on two different days, and confirm renv::status() or the package versions now disagree. If the content differs between two builds of a recipe believed to be pinned, the recipe is not yet pinned, and the honest level is still L1 whatever the FROM line claims.

ImportantThe honest level

When this chapter’s own practice names a digest, a dated snapshot, and a restored lockfile together, as it does in the Dockerfile above, it reaches L2 for the two layers a lockfile cannot reach. These are the operating system and system libraries, and the R runtime. It leaves L3, verification against a recorded baseline, entirely to Chapter 12.

A pinned recipe must also run where the reviewer works. In the R Consortium’s Pilot 4, a Shiny application submitted to the FDA with a Dockerfile, the agency’s statistical reviewers installed WSL and Docker Desktop on Windows. They noted that agency-issued laptops may not permit WSL or an unlicensed Docker Desktop, and found that the R version still decided whether the packages restored (U.S. Food and Drug Administration, Center for Drug Evaluation and Research, Office of Biostatistics, 2026). Their review, dated May 2026, concluded that containers so far may not give the robustness a regulatory submission needs (R Consortium, 2026; U.S. Food and Drug Administration, Center for Drug Evaluation and Research, Office of Biostatistics, 2026); the setup appendix covers such locked-down machines.

A recipe pins the base image by digest but still installs packages with a plain install.packages() against the live repository. Is this recipe’s claim to L2 honest? Say exactly what is and is not pinned.

Not honest as an L2 claim. The digest pins the operating system, the system libraries, and the R runtime, which is genuine progress on the two layers a lockfile cannot reach. But a plain install.packages() against the live repository still resolves ‘the current version’ to whatever is current on the day of that particular build. The recipe can therefore produce a different set of packages on two builds months apart, even though the FROM line is identical both times. Pinning the base and dating the package source are two separate refinements, and a recipe that does only the first has not finished the second.

7.8 Apple Silicon and multi-architecture images

The digest pinned in the previous section carries one complication, which matters to anyone who builds on a recent Mac. A single image tag, such as rocker/r-ver:4.4.0, need not name one fixed set of bytes. Docker images can be published as a manifest list, also called an image index. That is, one tag, or even one digest, points not directly at a filesystem but at a small table of entries. Each entry names a different CPU architecture built from the same recipe. When a client pulls the tag, the runtime inspects its own architecture and silently selects the matching entry. An amd64 host receives the amd64 build, an arm64 host receives the arm64 build, and the person who wrote FROM rocker/r-ver:4.4.0 never chose between them. This is what a multi-architecture image is: one name that resolves to different, independently built images depending on who is asking.

Not every Rocker image offers that choice. Rather than trust a secondary source, we checked directly, with docker buildx imagetools inspect. The digest on the showcase Dockerfile’s FROM line names an index with a linux/amd64 and a linux/arm64 image (verified). But rocker/tidyverse:4.4.0 and rocker/verse:4.4.0, the bases of the tidyverse and publishing profiles, publish linux/amd64 only (verified); neither carries an arm64 entry. An Apple Silicon Mac is an arm64 host. A plain docker build of the showcase Dockerfile on such a Mac therefore succeeds without any flag, natively, on the arm64 image (verified), while a recipe built on rocker/tidyverse or rocker/verse has no matching entry to select and needs --platform linux/amd64 to build at all.

The native build is the one to be wary of, because it succeeds quickly and yields a different image from the one a labmate on an Intel laptop, a CI runner, or a cluster node builds from the same FROM line. It starts from a different base image, and in our arm64 build of the showcase the packages compiled from source where an amd64 build installs binaries. An image built natively on a Mac and pushed to a registry will also not run on an x86 cluster. The flag is what makes a Mac build the same image the cluster runs, so this book passes --platform linux/amd64 to every build, whatever the base.

The --platform linux/amd64 flag requests the amd64 entry explicitly, overriding the host-architecture default. On an Apple Silicon host, Docker Desktop satisfies that request through QEMU, a CPU emulator that translates each amd64 instruction into the sequence of native arm64 instructions that has the same effect. Docker’s own documentation on multi-platform builds is direct about the cost: emulation with QEMU ‘can be much slower than native builds’, especially for compute-heavy work (Docker Inc., 2024). Every package compile and every renv::restore() inside the image pays this tax; a build that takes two minutes natively can take much longer under emulation. This is a real cost, worth planning a build around, but it is a cost in time, not in correctness. A QEMU-translated amd64 instruction still computes the amd64 result, so a container built this way runs the same program, only more slowly.

Emulation is not where a numerical risk would come from; the native build is. A native arm64 build of the showcase Dockerfile is not guaranteed to match an emulated amd64 build bit for bit. The reason is that a different architecture’s base image can, in principle, link a different BLAS, enable different vector instructions, or carry a different compiler default. Any of these can shift a floating-point result in its last few bits. None of that is new: it is the same category of hidden determinant, beneath the package layer, that the next section takes up for thread counts. The digest alone does not settle the question, because one index digest names both images. A digest together with a fixed platform does. The platform decides which entry of the index a build receives, and the digest decides that the entry is the same every time it asks. Pin both, or pin the digest of the platform-specific manifest, which names one filesystem by itself. This book pins the index digest and always passes --platform linux/amd64, the architecture of GitHub’s standard CI runners and of most HPC clusters.

A student on an Apple Silicon laptop builds this chapter’s showcase Dockerfile with --platform linux/amd64 and gets a working container. However, the build takes nine minutes instead of the ninety seconds a labmate on an Intel laptop reports. The student worries the slow build means the result cannot be trusted. Is that worry justified, and what, already taught in this chapter, actually decides whether the result is trustworthy?

The worry conflates two separate things. The nine-minute build is QEMU translating amd64 instructions into arm64 instructions, because the flag asked this arm64 host for the amd64 image. That cost is real, but it is a cost in time, not in correctness, since a translated amd64 instruction still computes the amd64 result. What actually decides trustworthiness is whether the FROM line names a digest rather than a tag, and whether both builds request the same platform. Here both do: the flag gives the student the amd64 entry, and the labmate’s Intel laptop is an amd64 host, so both laptops build on the identical base filesystem and restore the same packages, one of them slowly. The build time difference carries no information about whether the two containers agree. Had the student dropped the flag, the build would have been fast, native, and on a different base image. Had the FROM line named a tag, the two builds could silently diverge regardless of how long either one took, which is the whole reason this chapter pins by digest.

7.9 Environment-variable determinism

Are a fixed operating system and a fixed R enough? Not quite, because the same R on the same operating system can behave differently according to a handful of environment variables that the container inherits. Three of these deserve concrete illustration, because the failures they cause are silent and the fixes are one line each.

The first is the locale, carried in LANG and LC_ALL, which governs, among other things, how text is sorted and how dates and numbers are formatted for display. R’s own numeric parsing is not one of the things it governs. LC_NUMERIC is pinned to "C" inside R regardless of what LANG or LC_ALL say, so as.numeric('1,5') returns NA with a coercion warning under any locale the host or container sets. (We verified this by calling Sys.setlocale('LC_ALL', 'fr_FR.UTF-8') and confirming that Sys.getlocale('LC_NUMERIC') still reports 'C' and as.numeric('1,5') is still NA.) The risk is not that R silently reparses a number under a different convention; it is that data arriving from outside R already carries a convention baked in. A locale that uses a comma as the decimal mark, common across much of Europe, writes the number one and a half as 1,5 in a spreadsheet or CSV export. An ingest step that assumes a period decimal mark will misread it without erroring; an example is a hand-written regex that strips what it takes to be thousands separators. To make the failure concrete, consider the same numeric vector written under each convention by an external tool such as a spreadsheet application. The table below shows what a naive period-assuming cleaning step reads back from the comma-convention strings.

library(tibble)

x <- c(1.5, 2200.75, 0.333)

period <- formatC(x, format = 'f', digits = 3, big.mark = ',')

comma <- gsub(',', '#', period)
comma <- gsub('\\.', ',', comma)
comma <- gsub('#', '.', comma)

read_back <- as.numeric(gsub(',', '', comma))

decimal_demo <- tibble(
  original      = x,
  period_locale = period,
  comma_locale  = comma,
  parsed_value  = read_back
)

knitr::kable(decimal_demo)
Table 7.1: The same numbers written under a period decimal mark and a comma decimal mark, as a spreadsheet export might write them, and what a naive period-assuming cleaning step reads back from each. The comma-convention values are silently misread, with no error raised.
original period_locale comma_locale parsed_value
1.500 1.500 1,500 1500.00000
2200.750 2,200.750 2.200,750 2.20075
0.333 0.333 0,333 333.00000

The parsed values are wildly wrong, and nothing warns the analyst. The number 1.5 returns as 1500, the number 2200.75 as roughly 2.2, and the number 0.333 as 333, because the period-assuming cleaning step treats the European comma as noise and strips it. This is a failure of the ingest code, not of R’s parser. Even so, pinning LANG and LC_ALL in the image still matters for the parts of R that genuinely do depend on locale: collation and formatted output. Sorting the strings 'cote', 'côte', 'coté', 'coter' with sort() returns a different order under LC_ALL=C than under LC_ALL=fr_FR.UTF-8 (verified). Likewise, format(Sys.Date(), '%B') prints an English month name under one and a French month name under the other (verified). A report that sorts a table of names, or prints a month in running text, will read differently on two machines that disagree about locale even though every number in it was parsed identically. Fixing LANG and LC_ALL in the image removes that variability, which is why the Dockerfile above sets both to en_US.UTF-8.

The second is the time zone, carried in TZ. Date and time arithmetic depends on it, and an analysis that buckets events by calendar day will assign a late-evening event to different days in different time zones. Fixing TZ=UTC in the image makes the calculation independent of where the container runs.

The third is the thread count, carried in variables such as OMP_NUM_THREADS. Numerical libraries that implement linear algebra may split a computation across several threads. And because floating-point addition is not exactly associative, the order in which partial sums are combined can change the last bits of a result. Two runs of the same bootstrap or the same mixed model, one on four threads and one on eight, may therefore differ in the final digits. Which variable actually governs the summation order depends on the BLAS implementation the image carries: OPENBLAS_NUM_THREADS for OpenBLAS (which falls back to OMP_NUM_THREADS when it is unset), MKL_NUM_THREADS for the Intel MKL, and OMP_NUM_THREADS for the OpenMP-parallel sections. The rocker/r-ver images link R against the multithreaded OpenBLAS, not the single-threaded reference BLAS; in the image built above, sessionInfo() reports openblas-pthread/libblas.so.3. That is why the Dockerfile sets OPENBLAS_NUM_THREADS=1 alongside OMP_NUM_THREADS=1. OpenBLAS reads its own variable first, so a stray OPENBLAS_NUM_THREADS would override OMP_NUM_THREADS=1. Setting both to one together removes thread count as a source of variation in the order of summation. The image determines which BLAS is installed, but no rung of the ladder guarantees this layer. An L2 image run on a different CPU, or with these variables overridden at run time, can still move the last digits. The cost is a little speed, traded for run-to-run stability on the same image. Whether that trade is worth making is the analyst’s judgment, and a container lets that judgment be recorded and enforced instead of left to whatever the host defaults to.

A collaborator in Berlin and a collaborator in San Diego run the same containerized script on the same image and obtain identical package versions. Yet their daily case-count tables disagree by one case on several days, always at the boundaries between days. Which environment variable is the likely culprit, and why does pinning it in the image resolve the disagreement?

The likely culprit is TZ, the time zone. If the image does not fix it, the run can supply one: a -e TZ=... flag, a mounted /etc/localtime, or Apptainer, which binds the host’s /etc/localtime by default. An event recorded near midnight is then assigned to different calendar days in Berlin and San Diego. The daily buckets then differ at the day boundaries, which is exactly the pattern described. Setting TZ in the image, conventionally to UTC, makes the day assignment independent of the host, so both collaborators bucket the events identically. Note that identical package versions, that is, a shared L1, did nothing to prevent this: the failure is an environment failure, which is what the container layer exists to fix.

7.10 Profiles as base images

The choice of base image is, in practice, a choice from a short menu, and the framework this book uses names the entries profiles. A profile is a base-image bundle, and selecting one sets the FROM line and little else. Four profiles cover most needs.

The minimal profile builds on rocker/r-ver: R on Ubuntu with the development essentials and nothing more. It is the smallest base, and the right one when the analysis pulls in whatever it needs through the lockfile. The tidyverse profile builds on rocker/tidyverse, adding the tidyverse packages and pandoc, and is the natural default for data analysis. The rstudio profile builds on rocker/rstudio, adding the RStudio Server environment for those who prefer to work in the browser-based IDE. The publishing profile builds on rocker/verse, which carries a LaTeX toolchain, and is the base to choose when the deliverable is a rendered PDF manuscript.

The design intent is that the profiles differ in as few lines as possible. Moving a project from one profile to another changes the FROM line and, at most, a single system-installation line. The reproducibility-relevant configuration stays constant: the locale and time-zone variables, the dated snapshot, and the lockfile restore. The profile decides what the base carries, and the lockfile decides what is installed on top.

The archetypes of Chapter 5 map onto the profiles naturally, and the mapping is the concrete form of the first analyst judgment above. The same machinery, a digest-pinned base, a dated snapshot, a restored lockfile, and the determinism variables, serves every archetype; only the base changes.

  • A data-analysis archetype is well served by the tidyverse or minimal base, according to how much of its stack it draws from the base rather than the lockfile.
  • A manuscript archetype needs the publishing base, because rendering to PDF requires the LaTeX toolchain that rocker/verse carries and the lighter bases do not.
  • An R-package archetype needs very little: R and the check tools suffice, so the minimal base is the honest choice, and provisioning a LaTeX toolchain it never uses would be waste.
  • A simulation archetype often wants more cores than software, so the base may be minimal while the container is run with a larger core allocation. Here the analyst must weigh the determinism point above. More cores may speed the simulation while changing the last bits of a result, so the thread variables (OMP_NUM_THREADS and OPENBLAS_NUM_THREADS) and the seeding discipline of Chapter 5 deserve particular care.
  • A blog archetype renders many posts rather than one report, and is well served by the publishing or tidyverse base according to whether any post needs PDF output.

An R-package archetype is built against the publishing profile because the author ‘might as well have LaTeX available’. Name the concrete risk this choice creates, distinct from image size.

A package must be checked against a clean environment carrying only its declared dependencies, so that R CMD check or its equivalent catches a dependency the DESCRIPTION fails to declare. A rich publishing base can mask exactly that failure. The package’s code may rely, without declaring it, on a LaTeX tool or a system library the publishing base happens to carry. The check will then pass in this image and fail the moment the package is installed on a user’s machine that lacks that base. The minimal profile is the honest choice because it cannot hide an undeclared dependency behind extra software nobody asked for.

7.11 A first look at the two-layer team model

A container fixes an environment for one analyst. A team needs one shared environment, and this introduces a wrinkle we shall only sketch here and develop fully in Chapter 13. Building an image from a Rocker base and a full package set takes many minutes. It would be wasteful for every member of a lab, and every one of a lab’s projects, to rebuild the same base from scratch.

The remedy is a two-layer model. A team lead builds a comprehensive team image once, carrying the lab’s preferred packages, and pushes it to a shared registry. Each project then builds a thin second layer on top of that team image, rather than on the raw Rocker base. The first layer, the team image, is built once and reused everywhere; the second layer, the per-project image, adds only what the project needs and builds in seconds, where the full image takes minutes. Because the team image is itself pinned by digest, recorded in a committed file, and built and pulled for one platform (--platform linux/amd64), every member runs the same filesystem. ‘Works on my machine’ therefore cannot arise: there is, in the relevant sense, only one machine. A member who drops the flag on an Apple Silicon Mac falls outside that guarantee. The mechanics of building, pushing, digest-recording, and updating the team image are the business of Chapter 13.

Explain, to a lab member who asks why the team does not simply have every project build from the raw Rocker base, what the two-layer model buys beyond saved build minutes.

Saved time is real but not the main point. Building a comprehensive image once and pinning it by digest means every project in the lab, and every member working on any of them, starts from the same filesystem, provided all of them pull the same platform. The alternative is independently resolved installs, which could drift even when every project names the same package versions in its own lockfile. Rebuilding from the raw base every time reintroduces the chance that two builds diverge, when they run on different days against a live snapshot or a different system-library patch level. No lockfile would catch such a divergence, because it sits below the package layer. The shared team image is what makes ‘works on my machine’ inapplicable across the whole lab, not only within one project.

7.12 Worked example

We now follow a concrete case through, in the manner of the framework this book uses, which generates the Dockerfile so that the analyst does not write one by hand. A biostatistician is analyzing a registry cohort. The deliverable is a set of tables and figures, not a typeset manuscript, so the appropriate archetype is data analysis and the appropriate profile is minimal. That profile carries R and the essentials, with the analysis stack drawn from the lockfile. She scaffolds the project and builds the image. The shell session, shown as static text and never executed here, is short.

$ mkdir cohort-study && cd cohort-study
$ zzc minimal
$ make docker-build
$ make r

The zzc minimal step generates the project, including a Dockerfile pinned to a digest and a dated snapshot; make docker-build builds the image; and make r starts a container and drops her into an R session inside it. The generated Dockerfile is, in essence, the one shown earlier. It carries a digest-pinned FROM rocker/r-ver, the locale and time-zone and thread variables, and the dated snapshot wired into the repository options. It ends with a renv::restore() that installs the locked packages inside the fixed environment. The image records its own provenance in labels, the base image, its digest, and the snapshot date, so a later reader can see exactly what was pinned without leaving the image.

Now suppose a reviewer asks for a typeset manuscript with the analysis embedded. The archetype has shifted, and so should the profile. She regenerates against the publishing base:

$ zzc publishing
$ make docker-build

The FROM line now names rocker/verse, the LaTeX toolchain comes with it, and the manuscript renders to PDF inside the container. Almost nothing else in the recipe changed: the locale and thread variables, the dated snapshot, and the lockfile restore are identical. The same reproducibility machinery served both archetypes, and the move between them was a single changed line.

What has she gained, in the vocabulary of the ladder? Before the container, at L1, her collaborator’s restore could fail for a missing system library, or succeed and compute a different number under a different R. After it, at L2, the operating system, the system libraries, and the R are fixed and travel with the analysis, and the locale and time-zone and thread variables are declared rather than inherited. What she has not yet gained is verification, L3. An image that builds and a report that renders are not the same as a report whose numbers have been regenerated and shown to match a recorded baseline. That is the subject of Chapter 12.

Between the minimal and the publishing build in the worked example, name every line of the Dockerfile that had to change, and every piece of reproducibility machinery that stayed exactly as it was.

Only the FROM line changed, from the digest-pinned rocker/r-ver to the digest-pinned rocker/verse. Every other reproducibility-relevant line stayed fixed: the locale and time-zone and thread-count variables, the dated snapshot wired into the repository options, and the renv::restore() that installs the locked packages. This is the point of keeping the profiles cleanly separated from the rest of the recipe: changing what the deliverable is changes one line, not the discipline that makes either build reproducible.

The worked example’s generated Dockerfile is, in essence, the tested recipe of the section on making the image itself reproducible. It is reprinted below with four of its lines removed, and the two label values that would give lines 1 and 2 away masked. Write each missing line so that the recipe again reaches L2 when built with --platform linux/amd64.

# rocker/r-ver:4.4.0 is built on Ubuntu 22.04 (jammy), so the
# binary snapshot below must name jammy. Digest as of 2026-10-11.
# (1) ____: name the base image so that it cannot move

# (2) ____: the repository the installer fetches from
ARG RENV_VERSION=1.2.3

LABEL org.opencontainers.image.base.name="docker.io/rocker/r-ver:4.4.0" \
      org.opencontainers.image.base.digest="<the digest of line 1>" \
      cran.snapshot="<the date of line 2>"

ENV LANG=en_US.UTF-8 \
    LC_ALL=en_US.UTF-8 \
    TZ=UTC \
    # (3) ____: fix the thread count of OpenMP and of the BLAS
    RENV_CONFIG_REPOS_OVERRIDE=${PPM_SNAPSHOT}

# Later lines win, so this replaces Rocker's own snapshot date.
RUN echo "options(repos = c(CRAN = '${PPM_SNAPSHOT}'))" \
      >> /usr/local/lib/R/etc/Rprofile.site

WORKDIR /project
COPY renv.lock renv.lock

RUN Rscript -e "install.packages('renv')" \
 && Rscript -e "stopifnot(packageVersion('renv') == '${RENV_VERSION}')"

# (4) ____: install the locked package versions

The four missing lines of the worked example’s Dockerfile are these.

FROM rocker/r-ver:4.4.0@sha256:73adabf378930f8744f56bac1fe5e99870532eb4ced1a15075991bac909d21f3
ARG PPM_SNAPSHOT=https://packagemanager.posit.co/cran/__linux__/jammy/2026-06-27
    OMP_NUM_THREADS=1 \
    OPENBLAS_NUM_THREADS=1 \
RUN Rscript -e "renv::restore(library = .libPaths()[1], prompt = FALSE)"

Line (1) takes the digest, not the tag alone, because a tag is a mutable pointer that a maintainer rebuild can move. The digest names an image index, so it fixes one filesystem only together with --platform linux/amd64. Line (2) takes a dated snapshot naming jammy, because an undated URL can resolve differently from one build to the next, and a noble URL would install binaries built against other system libraries. Line (3) sets both thread counts, not OMP_NUM_THREADS alone, because the rocker/r-ver image links R against OpenBLAS, which reads OPENBLAS_NUM_THREADS ahead of OMP_NUM_THREADS. Line (4) restores the lockfile, because without it the image fixes the environment but not the package versions. The recipe would then not reach L1, and since the rungs are cumulative it would not be L2 either. The library argument puts the packages where every session in the container finds them.

7.13 The cohort, continued

The running cohort compendium of this book is, itself, a small research compendium: a cohort_raw.csv, a clean_cohort(), and a model fit on top. Whether it has reached L2 yet can be checked directly.

files_needed <- c('Dockerfile', 'renv.lock')
present <- file.exists(file.path('../..', files_needed))
names(present) <- files_needed
present
#> Dockerfile  renv.lock 
#>      FALSE       TRUE

Only renv.lock exists at the compendium’s root, so by this chapter’s standard the compendium is at L1. Reaching L2 needs nothing new. It needs only a Dockerfile that follows the showcase recipe built and verified earlier in this chapter, adapted to what the compendium’s own renv.lock records:

  • a FROM line naming a Rocker base appropriate to the compendium’s archetype, data analysis, and carrying the R the lockfile records, 4.6.1 here: so rocker/r-ver:4.6.1, pinned by its index digest and built with --platform linux/amd64, rather than the showcase’s rocker/r-ver:4.4.0. The two versions must match, because a lockfile restored under a different R is the mismatch this chapter opened with;
  • a dated-snapshot ARG, naming the Ubuntu release the chosen base actually runs, wired into RENV_CONFIG_REPOS_OVERRIDE as the showcase Dockerfile does. The release changes with the R version: rocker/r-ver:4.4.0 runs Ubuntu 22.04 (jammy), while rocker/r-ver:4.6.1 runs Ubuntu 24.04 (noble), as the CRAN setting in its image configuration shows;
  • the three determinism variables this chapter argued for, LANG/LC_ALL set to a fixed locale, TZ=UTC, and OMP_NUM_THREADS/OPENBLAS_NUM_THREADS set to a deliberate value, since the compendium’s bootstrap_ci() refits the model many times, and a multithreaded BLAS could move the last digits of the interval it reports;
  • a WORKDIR, a COPY renv.lock renv.lock, and the same two-step renv install and renv::restore() pattern, so the packages the compendium’s scripts load are restored inside the pinned environment.

None of this is built here, because building and verifying an image is slow and the showcase Dockerfile earlier in this chapter already did that verification once. What the check above adds is specific to the compendium: no Dockerfile is in place yet, and the gap is these four concrete items, not a vague ‘needs a Dockerfile’.

7.14 Collaborating with an LLM

A language model is a capable assistant for container work, and a Dockerfile it writes can look complete while lacking the pins this chapter requires. The analyst who delegates must verify, and the following three exchanges show what to watch for.

ImportantRestricted data

One rule comes first (habit 3). Never paste or upload protected health information, identifiable records, or data held under a data use agreement, nor outputs derived from them, into a model or a coding agent unless three conditions all hold. The institution has approved that endpoint for that class of data. The IRB protocol and the consent permit the processing. The data use agreement, or the provider’s terms, permits it. If any of the three is unclear, the answer is no.

The third condition is the one most often missed. Institutional approval of a tool does not override the terms under which a data provider released the data. NIH, for example, treats sharing controlled-access data through prompts with public generative AI tools, which it glosses as third-party tools, as a breach of the data use certification. It treats a model trained on such data as a data derivative, to be shared only with other approved users and not kept after the project closes (National Institutes of Health, 2025).

Describe the structure instead: the column names and types, or a small synthetic example generated from the data dictionary, never edited from real rows. A coding agent sees whatever files are in its working tree, so run it in a checkout or container where the real data is not mounted.

An agent also acts, so confine it to a branch and keep merges, pushes, and deposits for yourself (Section 2.10.1).

In container work, what an agent can see includes every host directory bind-mounted into a container it runs in, so a mount of the data directory exposes the data as surely as a copy in the working tree would.

Prompt. ‘Write me a Dockerfile for my R analysis.’

Watch for. Check whether the answer opens with FROM rocker/tidyverse:latest or a bare version tag, installs packages from the live repository, or sets none of the determinism variables. Every one of these is a reproducibility defect: the mutable tag, the undated installer, the absent locale and time zone. Such a recipe runs today and is not L2.

Verification. Confirm that the FROM line carries an @sha256: digest, not merely a tag. Confirm also that the in-image installer points at a dated snapshot, with a distribution codename that matches the base image’s Ubuntu release, and that renv::restore() is told to use it. Finally, confirm that LANG, LC_ALL, and TZ are set. Then build the image twice and confirm the two builds carry the same content, comparing the installed operating system and the R and package versions. This can be done, for instance, through renv::status() and the apt and R package version lists. Do not compare image digests, which differ across rebuilds even for a correctly pinned recipe because per-layer timestamps vary. If the content differs, the recipe is not pinned, whatever the model asserted. If an agent ran the two builds, read the two version lists yourself; its report that they match is not the comparison (Section 2.10.1).

A better prompt. ‘Write a Dockerfile for an R <version> analysis restored from the attached renv.lock. Pin the base image by digest; point the installer at a dated Package Manager snapshot for <codename>; set LANG, LC_ALL, and TZ; install nothing at run time. List the commands I should run to confirm that two builds install identical versions.’ The slots are filled from the lockfile and the base image’s Ubuntu release, as in ‘The cohort, continued’ above.

Prompt. ‘My container gives different numbers than my laptop. Why?’

Watch for. Check whether the answer reaches first for the code, suggesting a bug in the analysis, and overlooks the environment. The environment is the more probable cause, because the container was supposed to fix it and may have fixed it incompletely. Typical gaps are a missing locale variable, a different thread count, or an unpinned package version inside a pinned environment.

Verification. Compare the environment inside the container with the one outside it: inspect LANG, LC_ALL, TZ, and the thread-count variables in both, and compare the installed package versions against the lockfile. Do not accept a diagnosis of the code until the environment has been ruled out, because a difference the container failed to pin is the more likely explanation.

Prompt. ‘Which Rocker base should I use for my project?’

Watch for. Check whether the answer recommends a large, capable base, such as the verse or a data-science image, regardless of need. Over-provisioning inflates the image and obscures the real dependencies; under-provisioning, recommending a minimal base for a project that must render a PDF, produces a build that fails only when the manuscript is rendered.

Verification. Match the base to the archetype, not to the maximum. If the deliverable is a PDF manuscript, confirm the base carries a LaTeX toolchain, for instance by checking that the LaTeX tools are present in the built image. If it is an R package, confirm that R and the check tools suffice and resist any heavier base. The judgment is the first of this chapter’s analyst contributions, and it is not one to delegate.

7.15 Exercises

  1. Take any Rocker image on your machine or on Docker Hub and find both its tag and its content digest. Explain, in two or three sentences, what could change about the image named by the tag while the image named by the digest could not, and why a reproducible recipe pins the latter.

  2. You are handed a Dockerfile that begins FROM rocker/tidyverse:latest and installs packages with a plain install.packages() from the live repository. Identify every reason this recipe fails to reach L2, and rewrite the two instructions that most need fixing.

  3. For each of the five archetypes, data analysis, manuscript, R package, simulation, and blog, name the profile you would choose and justify the choice in one sentence. For the two archetypes where the choice is genuinely arguable, state the trade-off on both sides.

  4. Extend the executable table in this chapter to a date example. Construct two synthetic character vectors representing the same three dates under a month-first and a day-first convention, parse each under a single assumed convention, and show which dates are silently swapped. Relate the result to the role of TZ and locale in the image.

  5. Explain, to a colleague who has never met the idea, why setting OMP_NUM_THREADS=1 together with OPENBLAS_NUM_THREADS=1 can change the last digits of a bootstrap confidence interval or a mixed-model estimate. State clearly what is traded away by fixing it, and name one analysis where you would judge the trade worth making.

  6. A collaborator reports that after pulling your image and running renv::restore(), she still obtains different package versions from yours. The environment is pinned; the packages are not matching. Diagnose the most likely cause, and explain why a container alone, without the lockfile restored inside it, does not guarantee identical packages.

  7. (Cumulative) Run raw <- load_cohort('analysis/data/raw_data/cohort_raw.csv') and cohort <- clean_cohort(raw) from the compendium’s root. Report three things: nrow(cohort); the number of distinct values of cohort$sex after cleaning; and whether file.exists('Dockerfile') evaluates to TRUE or FALSE there, as ‘The cohort, continued’ above checks. Then name the instruction in this chapter’s showcase Dockerfile that pins the thread count, and say why it sets two variables rather than one.

  8. (Spacing) This exercise returns to the lockfile of Chapter 6, ‘Pinning Packages with renv’ (Chapter 6). Explain, in two or three sentences, what a pinned renv.lock guarantees about a result and what it does not, and name the specific gap this chapter’s container closes that the lockfile by itself cannot.

7.16 Solutions

Attempt an exercise before expanding its solution. The first asks you to inspect an image on your own machine, so the values will vary; the reasoning is what the box records.

The tag and the digest are found together by asking the registry, which needs no pull:

docker buildx imagetools inspect rocker/r-ver:4.4.0

The tag is rocker/r-ver:4.4.0. The Digest: line near the top is the index digest, the one a FROM line pins; the Manifests: list below it gives the digest of each platform’s image, linux/amd64 among them. The values may differ from any printed in this book, because the tag can since have been repointed. A copy already pulled reports the digest it was pulled under, which is not necessarily what the tag resolves to today:

docker pull --platform linux/amd64 rocker/r-ver:4.4.0
docker image inspect --format '{{index .RepoDigests 0}}' \
  rocker/r-ver:4.4.0

What can change under the tag. A tag is a mutable label, a name someone chose to point at an image. The maintainer can rebuild 4.4.0 to patch a system library, pick up a security update to the base Ubuntu layer, or correct a packaging mistake, and republish it under the same tag. Everything about the image can change: its system libraries, its preinstalled packages, its locale data, even its R patch level. What cannot change is the image named by the digest, because the digest is a content hash: an altered image hashes differently and is therefore a different image by construction, not by convention.

A reproducible recipe pins the digest because it wants that guarantee. Pinning the tag records an intention about which image to use; pinning the digest records the image. The cost is that a digest-pinned recipe does not receive security updates silently, which is usually the right trade for an analysis and the wrong one for a production service.

Every reason the recipe fails to reach L2.

  1. :latest is the most mutable tag there is. The image the recipe resolves to changes without notice, so two builds of the identical Dockerfile can produce different environments.
  2. A plain install.packages() draws from the live repository, so it installs whatever is current on the day of the build. The package versions are not pinned at all, which means the recipe does not even reach L1.
  3. No lockfile is restored, so there is no record of what was installed even after the fact.
  4. The determinism variables are absent: no LANG, no TZ, no thread count. The locale and time zone are inherited from the base and can shift with it.

The first two are the ones to rewrite. The FROM line becomes one line, but replacing the live install takes a short block, because a restore needs the lockfile copied into the image and a repository to fetch from:

FROM rocker/tidyverse:4.4.0@sha256:3e72037abda2a32d86021bbe5725e727f2c02233e4072557bc70c1e890e3471b

ENV RENV_CONFIG_REPOS_OVERRIDE=https://packagemanager.posit.co/cran/__linux__/jammy/2026-06-27

WORKDIR /project
COPY renv.lock renv.lock
RUN Rscript -e "install.packages('renv', repos = Sys.getenv('RENV_CONFIG_REPOS_OVERRIDE'))" \
 && Rscript -e "renv::restore(library = .libPaths()[1], prompt = FALSE)"

The FROM line pins the image by its own digest, the one rocker/tidyverse:4.4.0 resolved to on 2026-10-11. A digest names exactly one piece of content, here an index whose only image is for linux/amd64, so it cannot be borrowed from another image such as rocker/r-ver. When both a tag and a digest are given, Docker resolves the digest, and the tag is only a label for the human reader. The image is built on Ubuntu 22.04, so the snapshot names jammy, and it is published for linux/amd64 only, so on an Apple Silicon machine it runs under emulation and must be built with --platform linux/amd64. The block then copies the committed lockfile into a working directory, installs renv from the dated snapshot, and restores the recorded package set, fetching from that snapshot. We built this recipe on 2026-10-11 against a one-package lockfile (jsonlite 2.0.0) and the image reported jsonlite 2.0.0. A fuller repair would add the locale, time-zone, and thread-count variables and check the renv version, as the Dockerfile in the chapter does. Nevertheless, these lines are the ones that carry the recipe from unpinned to pinned.

Data analysis: tidyverse, because the analysis draws most of its stack from the base rather than the lockfile and the base saves the install. Manuscript: publishing, because rendering to PDF needs the LaTeX toolchain that rocker/verse carries and the lighter bases do not. R package: minimal, because a package must be checked against a clean environment carrying only its declared dependencies, and a rich base can mask a missing declaration. Simulation: minimal, because a simulation typically needs a small numeric stack and image size matters when the image is pulled onto many cluster nodes. Blog: tidyverse or publishing, depending on whether posts render to HTML alone.

The two genuinely arguable cases.

Data analysis. Tidyverse buys a fast build and a base whose contents are already tested together. Minimal buys a smaller image and, more importantly, honesty: everything the analysis uses comes through the lockfile, so the lockfile is a complete record rather than a supplement to an opaque base. The trade is build convenience against completeness of the record.

Blog. Publishing carries LaTeX, which a blog rendering only to HTML never uses, and it is a large image to pull and store for that. Tidyverse is lighter but leaves the blog unable to render a PDF version of a post without a rebuild. The trade is image size against format optionality, and it turns on whether any post will ever need PDF.

The general shape: a heavier base is faster to start with and less honest about what the analysis actually depends on.

library(tibble)
dates <- c('01/02/2026', '03/04/2026', '05/06/2026')
tibble(
  written     = dates,
  as_us       = format(as.Date(dates, '%m/%d/%Y'), '%d %B %Y'),
  as_european = format(as.Date(dates, '%d/%m/%Y'), '%d %B %Y')
)

Every one of the three parses successfully under both conventions and means something different under each: 01/02/2026 is 2 January under the day-first reading and 1 February under the month-first reading. No error is raised, because both readings are valid dates. This is the same failure mode as the decimal-mark table earlier in the chapter, and it is worse in one respect. The decimal-mark case produces visibly implausible magnitudes, whereas a swapped date is simply a different plausible date.

The dates that are silently swapped are exactly those where both components are twelve or under, which is roughly a third of a calendar year. A date such as 25/12/2026 fails to parse under the month-first convention and so announces itself; 01/02/2026 does not.

The relation to TZ and locale. Neither variable changes how an explicit format string parses, so a script that writes %d/%m/%Y is safe under any locale. They bite where the format is inferred: a locale-dependent parser, a spreadsheet export, or a read_csv() guessing a column type will resolve the ambiguity differently under different locale settings. Fixing LANG and TZ in the image removes that variability, which is why the chapter sets them. The stronger discipline is to state the format explicitly and never rely on inference, and to prefer ISO 8601 in any file the analysis writes, since 2026-02-01 is unambiguous under every convention.

Why the digits move. Floating-point addition is not associative. Adding a long column of numbers left to right can give a slightly different answer from adding it in pairs and combining, because each intermediate result is rounded. A multithreaded numerical library splits the sum across threads and combines the partial results, and the order in which the partials arrive depends on the thread count and on scheduling. So the same data can produce answers differing in the last few digits between a one-thread and an eight-thread run, and sometimes between two eight-thread runs. A bootstrap interval or a mixed-model estimate is built on many such reductions, so the difference propagates to the reported bounds.

Setting OMP_NUM_THREADS=1 together with OPENBLAS_NUM_THREADS=1, for the OpenBLAS the Rocker image carries, removes the variability by removing the parallelism: there is one summation order and it is the same every time on that image and CPU. Either variable alone can leave a source of threads in place: OPENBLAS_NUM_THREADS alone leaves other OpenMP code threaded, and OMP_NUM_THREADS alone yields to any OPENBLAS_NUM_THREADS set elsewhere.

What is traded away. Speed, and potentially a great deal of it. A mixed model on a large dataset, or a bootstrap with many replicates, can run several times faster across eight threads. Fixing the thread count to one converts a determinism problem into a wall-clock problem.

Where the trade is worth making. Any analysis whose outputs will be verified against recorded values, which is to say anything reaching for L3, since the verification compares numbers and the numbers must be stable. The concrete case is a regulatory submission. A fixed thread count for the final analysis makes the reported estimates reproducible bit for bit, and the extra hours are irrelevant against the cost of a discrepancy an auditor cannot explain. For exploratory work during development, the trade is usually not worth making.

One refinement: you can develop with threads and fix the count only for the final verified run, which recovers most of the speed and all of the determinism where it matters.

The most likely cause is that renv::restore() did not restore into the library the session is actually using, or did not run against the lockfile the collaborator believes it did. In practice this resolves to one of a few things. The project may have been opened from a directory where the lockfile is absent, so restore() had nothing to read. The container may mount a host renv cache or library that shadows the project library. RENV_PATHS_LIBRARY may point somewhere unexpected inside the image. Or the lockfile itself may not have been committed, so the collaborator restored an older version of it.

The diagnostic sequence is renv::status() to see whether the library and the lockfile agree, then .libPaths() to see which library is in force, then renv::project() to confirm which project renv believes it is in. Between them these locate all four causes.

Why the container alone does not guarantee identical packages. A container pins the environment: the operating system, the system libraries, and the R runtime. The packages installed into the image at build time are pinned by the image. However, any package the analysis installs or restores afterward is not, because it is resolved at run time against whatever the lockfile or the repository then says. The image and the lockfile do different jobs: in the chapter’s framing, the image is the L1-to-L2 step and the lockfile is the L0-to-L1 step.

The compact statement: the container guarantees the same floor, the lockfile guarantees the same packages, and an analysis needs both.

The solution for this exercise is in the instructor guide, which is distributed separately to course instructors. Self-study readers who want to check their answer can compare the three autogradable values against those reported in the chapter’s own ‘The cohort, continued’ section.

A pinned renv.lock guarantees that every R package the analysis loads is reinstalled at the exact version recorded, from the repository recorded, so two restores of the same lockfile install the same packages. It guarantees nothing about the operating system, the system libraries a package links against, or the version of R itself that runs those packages. None of those three is an R package. The lockfile’s R block records the R version, but the lockfile can install none of the three.

The specific gap this chapter’s container closes is exactly those three: the FROM line fixes the operating system and the system libraries, and the digest-pinned Rocker base fixes which R runtime runs the restored packages. The lockfile answers ‘which packages’ and the container answers ‘on what’. Consider this chapter’s own orientation story: the GDAL-dependent package that failed to install on a collaborator’s machine even though the lockfile pinned its version exactly. That is a failure the lockfile could not prevent and the container does.

7.17 Cheat sheet

Line or rule What it does
FROM image@sha256:... Pins the base by immutable content digest, not a mutable tag; for a multi-architecture index, it fixes one filesystem only together with a fixed --platform.
ARG PPM_SNAPSHOT=.../jammy/YYYY-MM-DD Names a dated package-repository snapshot matching the base’s Ubuntu release.
ENV RENV_CONFIG_REPOS_OVERRIDE=... Forces renv::restore() to fetch from the dated snapshot (habit 2).
ENV LANG=... LC_ALL=... Fixes locale-dependent sorting and formatted output.
ENV TZ=UTC Fixes day-boundary assignment for date/time arithmetic.
ENV OMP_NUM_THREADS=1, OPENBLAS_NUM_THREADS=1 Removes thread count as a source of floating-point variation, trading speed for stability.
WORKDIR /project Keeps renv out of the image root, where it refuses to initialize.
COPY renv.lock renv.lock + renv::restore() Restores the exact package set inside the fixed environment.
docker build --platform linux/amd64 Selects the amd64 entry of an index, so a Mac builds the same image as CI and the cluster; required on Apple Silicon for amd64-only bases such as rocker/tidyverse:4.4.0.
docker buildx imagetools inspect image:tag Asks the registry for the index digest a tag currently resolves to, and each platform’s manifest digest.
docker image inspect --format '{{index .RepoDigests 0}}' image:tag Reports the digest a local copy was pulled under, which may be stale.
Rule of thumb Compare content (renv::status(), package lists) across two builds to verify pinning; never compare digests, which differ by default even when content is identical (habit 4).

7.18 Further reading

The foundational case for containers in reproducible research is Boettiger (2015), which introduces Docker to a scientific-computing audience and is the natural first read for anyone new to the tool. The Rocker images themselves are documented by Boettiger & Eddelbuettel (2017), and the wider ecosystem of R containerization tooling is surveyed thoroughly by Nüst, Eddelbuettel, et al. (2020); both are worth consulting before building a base image of one’s own.

On making a container reproducible, the essential reference is Nüst, Sochat, et al. (2020), whose ten simple rules for writing Dockerfiles argue for version-specific image tags over :latest, explicit version pinning, and much else this chapter has drawn from. The published rules stop short of recommending a digest pin or a dated package snapshot (inspected); this chapter adds both as a stronger discipline on top of that checklist. Read the ten rules as a baseline against any Dockerfile one is asked to trust.

For the division of labor between the container and the package layer, return to Ushey & Wickham (2026) on renv, keeping in mind that its remit stops exactly where this chapter’s begins. The compendium structure into which both fit is the subject of Marwick et al. (2018), whose rrtools pairs a packaged analysis with a Dockerfile; its template has restored an renv lockfile since 2022. The alternatives to Docker as a runtime are taken up in Chapter 8. They range from the high-performance-computing runtime Apptainer (formerly Singularity) (Kurtzer et al., 2017) to the browser-based Binder (Project Jupyter et al., 2018) and the container-free Nix. The team-image model sketched here is developed in full in Chapter 13.