Skip to contents

Why Multi-Target Container Compilation Matters

Modern R projects span diverse deployment targets:

  • Reproducible Quarto manuscripts combining R, Python (reticulate/Jupyter), LaTeX PDF output, and spatial or graphics libraries (sf, ragg).
  • Production Shiny applications requiring non-root containers, HTTP health checks, background async workers (mirai/promises), and a reverse proxy.
  • HPC Bayesian & compiled pipelines (cmdstanr, RTMB, rjags, Rcpp, rextendr) where university clusters run Apptainer / Singularity rather than rootful Docker.

rcapsule compiles all three targets from a single static project scan and verifies every emitted specification against its built-in security and reproducibility linter.

1. Quarto Manuscript with LaTeX, Python, and Stan

library(rcapsule)

q_dir <- tempfile("rcapsule_quarto_demo_")
dir.create(q_dir)

writeLines(
  c(
    "project:",
    "  type: manuscript",
    "format:",
    "  pdf:",
    "    pdf-engine: pdflatex"
  ),
  file.path(q_dir, "_quarto.yml")
)

writeLines(
  c(
    "---",
    "title: 'Spatial Bayesian Modeling Manuscript'",
    "format: pdf",
    "---",
    "",
    "```{r}",
    "library(sf)",
    "library(ragg)",
    "library(ggplot2)",
    "```",
    "",
    "```{python}",
    "import numpy as np",
    "```",
    "",
    "```{stan}",
    "parameters { real alpha; }",
    "model { alpha ~ normal(0, 1); }",
    "```"
  ),
  file.path(q_dir, "manuscript.qmd")
)
writeLines(c("numpy==1.26.4", "scipy==1.13.0"), file.path(q_dir, "requirements.txt"))

sc_q <- scan_project(q_dir)
sc_q
#> 
#> ── rcapsule Project Scan: rcapsule_quarto_demo_1eb111f641d2 ────────────────────
#> • Path: /tmp/Rtmp8DjzZ2/rcapsule_quarto_demo_1eb111f641d2
#> • Project type: "quarto" (roles: quarto)
#> • R version: "4.6.2" | renv.lock: FALSE | DESCRIPTION: FALSE
#> • Entrypoint: "manuscript.qmd"
#> • Files scanned: 3
#> 
#> ── R Packages (3 non-base) ──
#> 
#> ggplot2, ragg@1.5.2, sf
#> 
#> ── Detected Toolchains (5) ──
#> 
#> cpp, cmdstan, python, quarto, latex
#> 
#> ── OS System Dependencies (25 apt packages) ──
#> 
#> build-essential, ca-certificates, curl, g++, gdal-bin, libfreetype6-dev,
#> libfribidi-dev, libgdal-dev, libgeos-dev, libharfbuzz-dev, libjpeg-dev,
#> libpng-dev, libproj-dev, libsqlite3-dev, libtbb-dev, libtiff5-dev,
#> libudunits2-dev, make, perl, python3, python3-dev, python3-pip, python3-venv,
#> wget, xz-utils

df_q <- compile_dockerfile(sc_q, r_version = "4.4.1", platform = "linux/amd64", use_ppm = TRUE)
lint_container_spec(df_q)
#> 
#> ── rcapsule Container Lint (dockerfile): PASS ──────────────────────────────────
#> Errors: 0 | Warnings: 0 | Info: 0
#> ✔ No issues found.
cat(paste(df_q$lines[1:45], collapse = "\n"))
#> # syntax=docker/dockerfile:1.7
#> # Generated by rcapsule 0.6.0
#> # Project: rcapsule_quarto_demo_1eb111f641d2 (quarto) | R 4.4.1
#> FROM --platform=linux/amd64 rocker/r-ver:4.4.1 AS builder
#> ENV DEBIAN_FRONTEND=noninteractive \
#>     TZ=UTC \
#>     LANG=C.UTF-8 \
#>     LC_ALL=C.UTF-8 \
#>     R_REPOS=https://packagemanager.posit.co/cran/__linux__/jammy/2026-01-15
#> # 1. OS system dependencies (build + runtime)
#> RUN apt-get update \
#>     && apt-get install -y --no-install-recommends \
#>       build-essential \
#>       ca-certificates \
#>       curl \
#>       g++ \
#>       gdal-bin \
#>       libfreetype6-dev \
#>       libfribidi-dev \
#>       libgdal-dev \
#>       libgeos-dev \
#>       libharfbuzz-dev \
#>       libjpeg-dev \
#>       libpng-dev \
#>       libproj-dev \
#>       libsqlite3-dev \
#>       libtbb-dev \
#>       libtiff5-dev \
#>       libudunits2-dev \
#>       make \
#>       perl \
#>       python3 \
#>       python3-dev \
#>       python3-pip \
#>       python3-venv \
#>       wget \
#>       xz-utils \
#>     && rm -rf /var/lib/apt/lists/*
#> # 2. Quarto CLI (1.5.57)
#> ARG QUARTO_VERSION=1.5.57
#> RUN ARCH=$(dpkg --print-architecture) \
#>     && mkdir -p /opt/quarto \
#>     && curl -fsSL "https://github.com/quarto-dev/quarto-cli/releases/download/v${QUARTO_VERSION}/quarto-${QUARTO_VERSION}-linux-${ARCH}.tar.gz" \
#>        -o /tmp/quarto.tar.gz \
#>     && tar -xzf /tmp/quarto.tar.gz -C /opt/quarto --strip-components=1 \

Notice how compile_dockerfile() automatically resolves libgdal-dev, libgeos-dev, libproj-dev, libfreetype6-dev, Quarto CLI, TinyTeX, a Python virtual environment (--no-cache-dir), and CmdStan in cache-optimal layers.

2. Production Shiny + Async Worker + Reverse Proxy Stack

When scan_project() detects a Shiny application (app.R or ui.R/server.R) alongside async workers (worker.R, mirai, promises), compile_compose() generates a hardened three-service stack (app, worker, and a pinned caddy:2.8.4-alpine reverse proxy) with no-new-privileges, health checks, and resource limits:

s_dir <- tempfile("rcapsule_shiny_demo_")
dir.create(s_dir)

writeLines(
  c(
    "library(shiny)",
    "library(bslib)",
    "library(mirai)",
    "ui <- page_sidebar(title = 'Forecast Dashboard', sidebar = sidebar('Inputs'), 'Plot')",
    "server <- function(input, output, session) {}",
    "shinyApp(ui, server)"
  ),
  file.path(s_dir, "app.R")
)
writeLines("library(mirai)\ndaemons(2)", file.path(s_dir, "worker.R"))

sc_s <- scan_project(s_dir)
comp_s <- compile_compose(sc_s, port = 3838L, proxy_port = 8080L)
lint_container_spec(comp_s)
#> 
#> ── rcapsule Container Lint (compose): PASS ─────────────────────────────────────
#> Errors: 0 | Warnings: 0 | Info: 0
#> ✔ No issues found.
cat(comp_s$content)
#> # Generated by rcapsule 0.6.0
#> # Project: rcapsule_shiny_demo_1eb141a722c0 (shiny)
#> services:
#>   app:
#>     build:
#>       context: '.'
#>       dockerfile: Dockerfile
#>     image: rcapsule_shiny_demo_1eb141a722c0:0.1.0
#>     restart: unless-stopped
#>     environment:
#>       TZ: UTC
#>       LC_ALL: C.UTF-8
#>       SHINY_PORT: '3838'
#>       R_CONFIG_ACTIVE: ${R_CONFIG_ACTIVE:-production}
#>     volumes:
#>       - ./data:/capsule/data:ro
#>       - capsule-output:/capsule/output
#>     security_opt:
#>       - no-new-privileges:true
#>     healthcheck:
#>       test:
#>         - CMD
#>         - curl
#>         - -fsS
#>         - http://127.0.0.1:3838/
#>       interval: 30s
#>       timeout: 5s
#>       retries: 3
#>       start_period: 15s
#>     deploy:
#>       resources:
#>         limits:
#>           cpus: '2.0'
#>           memory: 2G
#>     networks:
#>       - capsule-net
#>     expose:
#>       - '3838'
#>   worker:
#>     build:
#>       context: '.'
#>       dockerfile: Dockerfile
#>     image: rcapsule_shiny_demo_1eb141a722c0:0.1.0
#>     command:
#>       - Rscript
#>       - worker.R
#>     restart: unless-stopped
#>     environment:
#>       TZ: UTC
#>       LC_ALL: C.UTF-8
#>       SHINY_PORT: '3838'
#>       R_CONFIG_ACTIVE: ${R_CONFIG_ACTIVE:-production}
#>       CAPSULE_ROLE: worker
#>     volumes:
#>       - ./data:/capsule/data:ro
#>       - capsule-output:/capsule/output
#>     security_opt:
#>       - no-new-privileges:true
#>     healthcheck:
#>       test:
#>         - CMD
#>         - Rscript
#>         - -e
#>         - quit(status = 0)
#>       interval: 30s
#>       timeout: 5s
#>       retries: 3
#>       start_period: 15s
#>     deploy:
#>       resources:
#>         limits:
#>           cpus: '2.0'
#>           memory: 2G
#>     networks:
#>       - capsule-net
#>   proxy:
#>     image: caddy:2.8.4-alpine
#>     restart: unless-stopped
#>     command:
#>       - caddy
#>       - reverse-proxy
#>       - --from
#>       - :80
#>       - --to
#>       - http://app:3838
#>     ports:
#>       - 8080:80
#>     depends_on:
#>       app:
#>         condition: service_healthy
#>     security_opt:
#>       - no-new-privileges:true
#>     healthcheck:
#>       test:
#>         - CMD
#>         - wget
#>         - --spider
#>         - -q
#>         - http://127.0.0.1:80/
#>       interval: 30s
#>       timeout: 5s
#>       retries: 3
#>       start_period: 10s
#>     deploy:
#>       resources:
#>         limits:
#>           cpus: '0.5'
#>           memory: 256M
#>     networks:
#>       - capsule-net
#> volumes:
#>   capsule-output: {}
#> networks:
#>   capsule-net:
#>     driver: bridge

3. Bayesian & Compiled HPC Recipe for Apptainer

On university HPC clusters where Docker is unavailable, compile_apptainer() produces an Apptainer .def recipe complete with Bootstrap: docker, pinned base tags, set -euo pipefail, HPC bind directories (/scratch, /work, /data), non-root read permissions, %runscript, and %test:

h_dir <- tempfile("rcapsule_hpc_demo_")
dir.create(file.path(h_dir, "src"), recursive = TRUE)

writeLines(
  c(
    "library(cmdstanr)",
    "library(RTMB)",
    "library(Rcpp)",
    "m <- cmdstanr::cmdstan_model('model.stan')"
  ),
  file.path(h_dir, "run.R")
)
writeLines("parameters { real mu; } model { mu ~ normal(0, 1); }", file.path(h_dir, "model.stan"))
writeLines("#include <Rcpp.h>", file.path(h_dir, "src", "kernel.cpp"))

sc_h <- scan_project(h_dir)
def_h <- compile_apptainer(sc_h, r_version = "4.4.1")
lint_container_spec(def_h)
#> 
#> ── rcapsule Container Lint (apptainer): PASS ───────────────────────────────────
#> Errors: 0 | Warnings: 0 | Info: 0
#> ✔ No issues found.
cat(def_h$content)
#> # Generated by rcapsule 0.6.0
#> # Project: rcapsule_hpc_demo_1eb115f0c4e5 (analysis) | R 4.4.1
#> Bootstrap: docker
#> From: rocker/r-ver:4.4.1
#> 
#> %labels
#>     Project rcapsule_hpc_demo_1eb115f0c4e5
#>     ProjectType analysis
#>     RVersion 4.4.1
#>     GitRevision uncommitted
#>     CreatedBy rcapsule-0.6.0
#> 
#> %files
#>     . /capsule
#> 
#> %environment
#>     export LC_ALL=C.UTF-8
#>     export LANG=C.UTF-8
#>     export TZ=UTC
#>     export CAPSULE_DIR=/capsule
#>     export CMDSTAN=/opt/cmdstan/cmdstan-2.35.0
#> 
#> %post
#>     set -euo pipefail
#>     export DEBIAN_FRONTEND=noninteractive
#>     export TZ=UTC
#>     export R_REPOS=https://packagemanager.posit.co/cran/2026-01-15
#> 
#>     # OS system dependencies
#>     apt-get update \
#>     && apt-get install -y --no-install-recommends \
#>       build-essential \
#>       ca-certificates \
#>       curl \
#>       g++ \
#>       gfortran \
#>       libtbb-dev \
#>       libtbb12 \
#>       make \
#>     && rm -rf /var/lib/apt/lists/*
#> 
#>     cd /capsule
#>     # Install discovered R packages
#>     Rscript -e "install.packages(c('cmdstanr', 'Rcpp', 'RTMB'), repos = Sys.getenv('R_REPOS'), Ncpus = parallel::detectCores())"
#> 
#>     # CmdStan (2.35.0)
#>     mkdir -p /opt/cmdstan
#>     Rscript -e "if (!requireNamespace('cmdstanr', quietly = TRUE)) install.packages('cmdstanr', repos = c('https://stan-dev.r-universe.dev', Sys.getenv('R_REPOS'))); cmdstanr::install_cmdstan(dir = '/opt/cmdstan', version = '2.35.0', cores = parallel::detectCores(), quiet = FALSE)"
#> 
#>     # HPC compatibility: create standard bind mount points & non-root read permissions
#>     mkdir -p /scratch /work /data
#>     chmod -R a+rX /capsule
#> 
#> %runscript
#>     cd /capsule
#>     exec Rscript "run.R" "$@"
#> 
#> %test
#>     set -euo pipefail
#>     R --version
#>     Rscript -e "pkgs <- c('cmdstanr', 'Rcpp', 'RTMB'); missing <- pkgs[!vapply(pkgs, requireNamespace, logical(1), quietly = TRUE)]; if (length(missing)) stop('Missing packages: ', paste(missing, collapse = ', '))"
#>     test -d "$CMDSTAN"

4. Static Auditing of Hand-Written Container Specs

lint_container_spec() can also audit existing hand-written Dockerfiles, Compose files, or Apptainer definitions to catch reproducibility and security pitfalls before deployment:

problematic_dockerfile <- c(
  "FROM rocker/r-ver:latest",
  "ENV API_KEY=hardcoded_token_value",
  "RUN apt-get update && apt-get install -y libgdal-dev",
  "COPY . /app",
  "RUN Rscript -e \"renv::restore()\""
)

lint_container_spec(problematic_dockerfile, type = "dockerfile")
#> 
#> ── rcapsule Container Lint (dockerfile): FAIL ──────────────────────────────────
#> Errors: 2 | Warnings: 4 | Info: 2
#> ✖ [DF001] (line 1) Base image 'rocker/r-ver:latest' uses mutable ':latest' tag.
#> ! [DF008] (line 2) Potential hardcoded secret detected in ENV instruction.
#> ! [DF002] (line 3) apt-get install without cleaning /var/lib/apt/lists/* bloats image layers.
#> ! [DF003] (line 3) apt-get install missing '--no-install-recommends'.
#> ! [DF007] (line 4) Copying full project context before renv::restore() busts Docker build cache on every edit.
#> ✖ [DF004] (line 1) Final stage has no non-root USER instruction; container runs as root.
#> ℹ [DF005] (line 1) No HEALTHCHECK instruction in final stage.
#> ℹ [DF009] (line 1) No WORKDIR instruction in final stage.