nerdctl icon indicating copy to clipboard operation
nerdctl copied to clipboard

build: support resource limit flags (--memory, --cpu-*, --ulimit, --shm-size, --cgroup-parent)

Open okhowang opened this issue 3 weeks ago • 1 comments

What is the problem you're trying to solve

nerdctl build currently exposes no resource limit flags at all, while both docker build and nerdctl run do. Passing any of them fails with unknown flag:

$ nerdctl build --memory 2g -t foo .
unknown flag: --memory

$ nerdctl build --ulimit nofile=1024:2048 -t foo .
unknown flag: --ulimit

$ nerdctl build --cgroup-parent foo.slice -t foo .
unknown flag: --cgroup-parent

For comparison, nerdctl run has the full set registered in cmd/nerdctl/container/container_run.go (--cpus, --memory, --memory-swap, --cpu-shares, --cpu-quota, --cpu-period, --cpuset-cpus, --cpuset-mems, --ulimit, --shm-size, --cgroup-parent), but cmd/nerdctl/builder/builder_build.go registers none of them.

This matters in practice on shared/CI machines: a single RUN npm run build or a large compile step can exhaust host memory or saturate all CPUs, and there is currently no way to constrain it from the nerdctl side. Today the only workaround is to limit buildkitd as a whole via systemd (MemoryMax= / CPUQuota=) or max-parallelism in buildkitd.toml, which is coarse-grained and not per-build.

Two secondary documentation issues:

  • docs/command-reference.md:810 says Unimplemented docker build flags: --squash only. Per the convention stated at the top of that document ("Unlisted docker CLI flags are unimplemented yet"), these flags are technically covered, but given that nerdctl run documents the exact same flags as supported, the asymmetry is easy to miss. It would help to list them explicitly.
  • docs/command-reference.md:1776 already lists --memory as unimplemented for nerdctl compose build, so compose build would need the same treatment once build gains the flags.

Describe the solution you'd like

Add the Docker-compatible resource flags to nerdctl build (and later nerdctl compose build) and translate them into BuildKit frontend attributes. The BuildKit side already supports all of this — nerdctl only needs to pass the options through, the same way it already does for --target, --platform, --add-host and --network.

The dockerfile frontend attribute keys (from frontend/dockerui/config.go) are:

docker build flag BuildKit frontend attr Available since
--cgroup-parent cgroup-parent BuildKit v0.10.0
--ulimit ulimit long-standing
--shm-size shm-size long-standing
--memory memory BuildKit v0.31.0
--memory-swap memswap BuildKit v0.31.0
--cpu-shares cpushares BuildKit v0.31.0
--cpu-period cpuperiod BuildKit v0.31.0
--cpu-quota cpuquota BuildKit v0.31.0
--cpuset-cpus cpusetcpus BuildKit v0.31.0
--cpuset-mems cpusetmems BuildKit v0.31.0

cgroup-parent is read straight into Config.CgroupParent in frontend/dockerui/config.go (bc.CgroupParent = opts[keyCgroupParent]); the rest are parsed by parseUlimits() / parseShmSize() / parseLinuxResources() in frontend/dockerui/attr.go into Config.Ulimits, Config.ShmSize and Config.LinuxResources.

Note that cgroup-parent is a much older feature than the rest: introduced in commit c82ef27 ("cgroup-parent support", 2021-10-27), first released in BuildKit v0.10.0, gated behind exec.meta.cgroup.parent (CapExecMetaCgroupParent). It is effectively available on every buildkitd in the field. buildkitd.toml also has a server-side worker.oci.defaultCgroupParent, which a per-build attr overrides (executor/oci/spec.go: if len(meta.CgroupParent) > 0 { ... }).

Since nerdctl build shells out to buildctl, the change is confined to pkg/cmd/builder/build.go, following the existing pattern:

buildctlArgs = append(buildctlArgs, "--opt=memory="+strconv.FormatInt(memBytes, 10))
buildctlArgs = append(buildctlArgs, "--opt=ulimit="+strings.Join(ulimits, ","))

buildctl has no dedicated flags for these; they go through the generic --opt key=value (cmd/buildctl/build.go → build.ParseOpt → SolveOpt.FrontendAttrs).

Suggested split into two PRs, since the two groups have very different compatibility requirements:

  1. --cgroup-parent, --ulimit and --shm-size — these attrs have been in BuildKit for a long time (cgroup-parent since v0.10.0), so they work against currently deployed buildkitd versions and are low risk. --cgroup-parent does need path-format conversion though, see below.
  2. --memory / --memory-swap / --cpu-* / --cpuset-* — requires BuildKit >= v0.31.0 and needs capability handling (see below).

Implementation notes worth flagging up front:

  • Unit parsing is on nerdctl. The memory and memswap attrs are parsed with plain strconv.ParseInt in BuildKit, i.e. raw bytes with no suffix support. nerdctl must convert 2g → 2147483648 itself (units.RAMInBytes, as pkg/cmd/container/run_cgroup_linux.go already does) before passing the attr. Passing --memory=2g straight through would fail with invalid memory value: 2g.

  • Name mismatch: --memory-swap maps to memswap, not memory-swap.

  • --cgroup-parent cannot be passed through verbatim. The two sides build the cgroup path differently, so a naive passthrough would silently produce a wrong path under systemd:

    systemd cgroupfs
    nerdctl run (generateCgroupPath) requires a xxx.slice suffix, errors out otherwise; emits <parent>:nerdctl:<id> filepath.Join(parent, id) → /<parent>/<id>
    BuildKit (executor/oci/spec.go) only if the value contains .slice and ends with :; emits <parent><id> filepath.Join("/", parent, "buildkit", id) → /<parent>/buildkit/<id>

    So --cgroup-parent foo.slice — the form nerdctl run accepts — does not end with :, falls into BuildKit's else branch and yields the cgroupfs-style path /foo.slice/buildkit/<id> instead of a systemd slice. nerdctl would need to emit foo.slice:buildkit: (or similar) when the cgroup manager is systemd. Note also that BuildKit inserts an extra buildkit path component in the cgroupfs case, and performs no validation, whereas nerdctl run rejects a non-.slice parent outright. Worth reusing/adapting generateCgroupPath() rather than hand-rolling the conversion.

  • Validation ranges differ slightly from run: memory must be > 0; memswap must be -1 (unlimited) or > 0; cpusetcpus / cpusetmems are validated by util/cpuset.Validate.

  • --ulimit is CSV-encoded in a single attr, not repeated: --opt ulimit=nofile=1024:2048,nproc=100 (csvvalue.Fields + units.ParseUlimit). Note that nerdctl run --ulimit is a StringSlice, so the encoding differs between the two commands.

  • --cpus has no BuildKit equivalent. Docker's classic builder doesn't accept it either, and buildx didn't add it. Either omit it, or desugar it to cpuquota/cpuperiod like oci.WithCPUCFS does in run_cgroup_linux.go. Omitting it is probably the more honest option.

  • Capability negotiation: BuildKit gates the resource attrs behind exec.meta.linux.resources (solver/pb/caps.go). Against an older buildkitd the attrs would be rejected, so nerdctl should either check the cap or surface a clear error rather than failing opaquely. pkg/buildkitutil.GetWorkerLabels() already demonstrates querying the daemon via buildctl debug workers.

  • Pinned # syntax= directives bypass the built-in frontend. nerdctl always passes --frontend=dockerfile.v0, whose version tracks buildkitd, but a Dockerfile pinning # syntax=docker/dockerfile:<older> will load an external frontend image instead. The resource attrs require the dockerfile/1.25.0 frontend or newer, so a pinned older image would silently drop them. Worth a note in the docs.

  • Semantics must be documented clearly: these are per-step limits, not a budget for the whole build. BuildKit executes steps in parallel, so --memory=2g means each RUN may use up to 2 GB and the aggregate can far exceed that. This is a real footgun and differs from what users expect from docker build --memory.

Additional context

Upstream work this builds on:

  • moby/buildkit#593 — Add build cgroup settings (the original long-standing request)
  • moby/buildkit#6569 — solver: add per-step CPU and memory resource limits, merged 2026-05-27. Deliberately keeps the limits out of the cache key (in pb.OpMetadata) and merges to the most permissive value when the same step carries conflicting limits across jobs (solver/llbsolver/ops/merge_linux_resources.go). Linux only; Windows/FreeBSD/Darwin return an explicit error. Verified locally that v0.31.0 is the first release tag containing the merge commit (git tag --contains f5ec43c | grep '^v0\.'), and dockerfile/1.25.0 the first frontend tag.
  • docker/buildx#3876 — exposes --memory, --memory-swap, --cpu-shares, --cpu-period, --cpu-quota, --cpuset-cpus, --cpuset-mems plus bake target attributes and compose x-bake fields. Shipped in buildx v0.35.0.

Known upstream limitation — rootless. moby/buildkit#7287 (open) reports that per-step resource limits are silently ignored in rootless mode, even with cgroup v2 delegation: util/rootless/specconv/specconv_linux.go ToRootless() unconditionally clears spec.Linux.Resources and spec.Linux.CgroupsPath, while the daemon still advertises exec.meta.linux.resources. The build succeeds with no warning. Fix PRs #7288 (warn) and #7289 (apply limits when cgroup v2 is delegated) are not merged yet.

This affects --cgroup-parent too, and not just the new resource flags: it is spec.Linux.CgroupsPath that ToRootless() clears, which is exactly where cgroup-parent lands. BuildKit's own test acknowledges this — testCgroupParent in frontend/dockerfile/dockerfile_resources_test.go starts with if sb.Rootless() { t.SkipNow() }. So the rootless caveat applies to the whole flag group in this issue, including the "low risk" first PR.

This is directly relevant to nerdctl, since rootless + containerd-rootless-setuptool.sh install-buildkit is a first-class supported setup. Clearing CgroupsPath also disables resource sampling / OOM detection and causes runc kill to miss non-init processes on cancellation. Question for maintainers: should nerdctl warn when these flags are used against a rootless BuildKit worker (detectable via worker labels), or just document the caveat and wait for the upstream fix?

Prior art in this repo: I could not find an existing issue tracking build-time resource limits. The closest related items are #5066 (nerdctl update --cpus wrote cpuset instead of quota/period — closed) and #4185 (TestRunBlkioSettingCgroupV2 non-functional on EL9 — open), both runtime-side.

One more thing worth noting about --cgroup-parent: BuildKit deliberately excludes it from provenance attestations — it is listed in hostSpecificArgs in solver/llbsolver/provenance/predicate.go alongside platform and image-resolve-mode. So passing it does not affect build reproducibility metadata.

Created with: CodeBuddy

okhowang avatar Nov 10 '26 02:11 okhowang

Thx for the detailed write-up. If nobody's on it, I'd like to take the first PR (--ulimit, --shm-size, --cgroup-parent), reusing generateCgroupPath for the systemd conversion like you suggested. For rootless I'd document the caveat for now rather than add a warning, since moby/buildkit#7288/#7289 may change the behavior anyway. Happy to switch to a warning if maintainers prefer.

cvas22 avatar Nov 11 '26 22:11 cvas22