1 # pkgs.dockerTools {#sec-pkgs-dockerTools}
3 `pkgs.dockerTools` is a set of functions for creating and manipulating Docker images according to the [Docker Image Specification v1.3.0](https://github.com/moby/moby/blob/46f7ab808b9504d735d600e259ca0723f76fb164/image/spec/spec.md#image-json-field-descriptions).
4 Docker itself is not used to perform any of the operations done by these functions.
6 ## buildImage {#ssec-pkgs-dockerTools-buildImage}
8 This function builds a Docker-compatible repository tarball containing a single image.
9 As such, the result is suitable for being loaded in Docker with `docker image load` (see [](#ex-dockerTools-buildImage) for how to do this).
11 This function will create a single layer for all files (and dependencies) that are specified in its argument.
12 Only new dependencies that are not already in the existing layers will be copied.
13 If you prefer to create multiple layers for the files and dependencies you want to add to the image, see [](#ssec-pkgs-dockerTools-buildLayeredImage) or [](#ssec-pkgs-dockerTools-streamLayeredImage) instead.
15 This function allows a script to be run during the layer generation process, allowing custom behaviour to affect the final results of the image (see the documentation of the `runAsRoot` and `extraCommands` attributes).
17 The resulting repository tarball will list a single image as specified by the `name` and `tag` attributes.
18 By default, that image will use a static creation date (see documentation for the `created` attribute).
19 This allows `buildImage` to produce reproducible images.
22 When running an image built with `buildImage`, you might encounter certain errors depending on what you included in the image, especially if you did not start with any base image.
24 If you encounter errors similar to `getProtocolByName: does not exist (no such protocol name: tcp)`, you may need to add the contents of `pkgs.iana-etc` in the `copyToRoot` attribute.
25 Similarly, if you encounter errors similar to `Error_Protocol ("certificate has unknown CA",True,UnknownCa)`, you may need to add the contents of `pkgs.cacert` in the `copyToRoot` attribute.
28 ### Inputs {#ssec-pkgs-dockerTools-buildImage-inputs}
30 `buildImage` expects an argument with the following attributes:
34 : The name of the generated image.
36 `tag` (String or Null; _optional_)
38 : Tag of the generated image.
39 If `null`, the hash of the nix derivation will be used as the tag.
41 _Default value:_ `null`.
43 `fromImage` (Path or Null; _optional_)
45 : The repository tarball of an image to be used as the base for the generated image.
46 It must be a valid Docker image, such as one exported by `docker image save`, or another image built with the `dockerTools` utility functions.
47 This can be seen as an equivalent of `FROM fromImage` in a `Dockerfile`.
48 A value of `null` can be seen as an equivalent of `FROM scratch`.
50 If specified, the layer created by `buildImage` will be appended to the layers defined in the base image, resulting in an image with at least two layers (one or more layers from the base image, and the layer created by `buildImage`).
51 Otherwise, the resulting image with contain the single layer created by `buildImage`.
54 Only **Env** configuration is inherited from the base image.
57 _Default value:_ `null`.
59 `fromImageName` (String or Null; _optional_)
61 : Used to specify the image within the repository tarball in case it contains multiple images.
62 A value of `null` means that `buildImage` will use the first image available in the repository.
65 This must be used with `fromImageTag`. Using only `fromImageName` without `fromImageTag` will make `buildImage` use the first image available in the repository.
68 _Default value:_ `null`.
70 `fromImageTag` (String or Null; _optional_)
72 : Used to specify the image within the repository tarball in case it contains multiple images.
73 A value of `null` means that `buildImage` will use the first image available in the repository.
76 This must be used with `fromImageName`. Using only `fromImageTag` without `fromImageName` will make `buildImage` use the first image available in the repository
79 _Default value:_ `null`.
81 `copyToRoot` (Path, List of Paths, or Null; _optional_)
83 : Files to add to the generated image.
84 Anything that coerces to a path (e.g. a derivation) can also be used.
85 This can be seen as an equivalent of `ADD contents/ /` in a `Dockerfile`.
87 _Default value:_ `null`.
89 `keepContentsDirlinks` (Boolean; _optional_)
91 : When adding files to the generated image (as specified by `copyToRoot`), this attribute controls whether to preserve symlinks to directories.
92 If `false`, the symlinks will be transformed into directories.
93 This behaves the same as `rsync -k` when `keepContentsDirlinks` is `false`, and the same as `rsync -K` when `keepContentsDirlinks` is `true`.
95 _Default value:_ `false`.
97 `runAsRoot` (String or Null; _optional_)
99 : A bash script that will run as root inside a VM that contains the existing layers of the base image and the new generated layer (including the files from `copyToRoot`).
100 The script will be run with a working directory of `/`.
101 This can be seen as an equivalent of `RUN ...` in a `Dockerfile`.
102 A value of `null` means that this step in the image generation process will be skipped.
104 See [](#ex-dockerTools-buildImage-runAsRoot) for how to work with this attribute.
107 Using this attribute requires the `kvm` device to be available, see [`system-features`](https://nixos.org/manual/nix/stable/command-ref/conf-file.html#conf-system-features).
108 If the `kvm` device isn't available, you should consider using [`buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage) or [`streamLayeredImage`](#ssec-pkgs-dockerTools-streamLayeredImage) instead.
109 Those functions allow scripts to be run as root without access to the `kvm` device.
113 At the time the script in `runAsRoot` is run, the files specified directly in `copyToRoot` will be present in the VM, but their dependencies might not be there yet.
114 Copying their dependencies into the generated image is a step that happens after `runAsRoot` finishes running.
117 _Default value:_ `null`.
119 `extraCommands` (String; _optional_)
121 : A bash script that will run before the layer created by `buildImage` is finalised.
122 The script will be run on some (opaque) working directory which will become `/` once the layer is created.
123 This is similar to `runAsRoot`, but the script specified in `extraCommands` is **not** run as root, and does not involve creating a VM.
124 It is simply run as part of building the derivation that outputs the layer created by `buildImage`.
126 See [](#ex-dockerTools-buildImage-extraCommands) for how to work with this attribute, and subtle differences compared to `runAsRoot`.
128 _Default value:_ `""`.
130 `config` (Attribute Set or Null; _optional_)
132 : Used to specify the configuration of the containers that will be started off the generated image.
133 Must be an attribute set, with each attribute as listed in the [Docker Image Specification v1.3.0](https://github.com/moby/moby/blob/46f7ab808b9504d735d600e259ca0723f76fb164/image/spec/spec.md#image-json-field-descriptions).
135 _Default value:_ `null`.
137 `architecture` (String; _optional_)
139 : Used to specify the image architecture.
140 This is useful for multi-architecture builds that don't need cross compiling.
141 If specified, its value should follow the [OCI Image Configuration Specification](https://github.com/opencontainers/image-spec/blob/main/config.md#properties), which should still be compatible with Docker.
142 According to the linked specification, all possible values for `$GOARCH` in [the Go docs](https://go.dev/doc/install/source#environment) should be valid, but will commonly be one of `386`, `amd64`, `arm`, or `arm64`.
144 _Default value:_ the same value from `pkgs.go.GOARCH`.
146 `diskSize` (Number; _optional_)
148 : Controls the disk size (in megabytes) of the VM used to run the script specified in `runAsRoot`.
149 This attribute is ignored if `runAsRoot` is `null`.
151 _Default value:_ 1024.
153 `buildVMMemorySize` (Number; _optional_)
155 : Controls the amount of memory (in megabytes) provisioned for the VM used to run the script specified in `runAsRoot`.
156 This attribute is ignored if `runAsRoot` is `null`.
158 _Default value:_ 512.
160 `created` (String; _optional_)
162 : Specifies the time of creation of the generated image.
163 This should be either a date and time formatted according to [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) or `"now"`, in which case `buildImage` will use the current date.
165 See [](#ex-dockerTools-buildImage-creatednow) for how to use `"now"`.
168 Using `"now"` means that the generated image will not be reproducible anymore (because the date will always change whenever it's built).
171 _Default value:_ `"1970-01-01T00:00:01Z"`.
173 `uid` (Number; _optional_)
175 : The uid of the user that will own the files packed in the new layer built by `buildImage`.
179 `gid` (Number; _optional_)
181 : The gid of the group that will own the files packed in the new layer built by `buildImage`.
185 `compressor` (String; _optional_)
187 : Selects the algorithm used to compress the image.
189 _Default value:_ `"gz"`.\
190 _Possible values:_ `"none"`, `"gz"`, `"zstd"`.
192 `includeNixDB` (Boolean; _optional_)
194 : Populate the nix database in the image with the dependencies of `copyToRoot`.
195 The main purpose is to be able to use nix commands in the container.
198 Be careful since this doesn't work well in combination with `fromImage`. In particular, in a multi-layered image, only the Nix paths from the lower image will be in the database.
200 This also neglects to register the store paths that are pulled into the image as a dependency of one of the other values, but aren't a dependency of `copyToRoot`.
203 _Default value:_ `false`.
205 `contents` **DEPRECATED**
207 : This attribute is deprecated, and users are encouraged to use `copyToRoot` instead.
209 ### Passthru outputs {#ssec-pkgs-dockerTools-buildImage-passthru-outputs}
211 `buildImage` defines a few [`passthru`](#chap-passthru) attributes:
213 `buildArgs` (Attribute Set)
215 : The argument passed to `buildImage` itself.
216 This allows you to inspect all attributes specified in the argument, as described above.
218 `layer` (Attribute Set)
220 : The derivation with the layer created by `buildImage`.
221 This allows easier inspection of the contents added by `buildImage` in the generated image.
225 : The tag of the generated image.
226 This is useful if no tag was specified in the attributes of the argument to `buildImage`, because an automatic tag will be used instead.
227 `imageTag` allows you to retrieve the value of the tag used in this case.
229 ### Examples {#ssec-pkgs-dockerTools-buildImage-examples}
231 :::{.example #ex-dockerTools-buildImage}
232 # Building a Docker image
234 The following package builds a Docker image that runs the `redis-server` executable from the `redis` package.
235 The Docker image will have name `redis` and tag `latest`.
238 { dockerTools, buildEnv, redis }:
239 dockerTools.buildImage {
243 copyToRoot = buildEnv {
246 pathsToLink = [ "/bin" ];
254 Cmd = [ "/bin/redis-server" ];
255 WorkingDir = "/data";
256 Volumes = { "/data" = { }; };
261 The result of building this package is a `.tar.gz` file that can be loaded into Docker:
265 (some output removed for clarity)
266 building '/nix/store/yw0adm4wpsw1w6j4fb5hy25b3arr9s1v-docker-image-redis.tar.gz.drv'...
268 tar: Removing leading `/' from member names
272 /nix/store/p4dsg62inh9d2ksy3c7bv58xa851dasr-docker-image-redis.tar.gz
274 $ docker image load -i /nix/store/p4dsg62inh9d2ksy3c7bv58xa851dasr-docker-image-redis.tar.gz
275 (some output removed for clarity)
276 Loaded image: redis:latest
280 :::{.example #ex-dockerTools-buildImage-runAsRoot}
281 # Building a Docker image with `runAsRoot`
283 The following package builds a Docker image with the `hello` executable from the `hello` package.
284 It uses `runAsRoot` to create a directory and a file inside the image.
286 This works the same as [](#ex-dockerTools-buildImage-extraCommands), but uses `runAsRoot` instead of `extraCommands`.
289 { dockerTools, buildEnv, hello }:
290 dockerTools.buildImage {
294 copyToRoot = buildEnv {
297 pathsToLink = [ "/bin" ];
302 echo "some content" > my-file
306 Cmd = [ "/bin/hello" ];
307 WorkingDir = "/data";
313 :::{.example #ex-dockerTools-buildImage-extraCommands}
314 # Building a Docker image with `extraCommands`
316 The following package builds a Docker image with the `hello` executable from the `hello` package.
317 It uses `extraCommands` to create a directory and a file inside the image.
319 This works the same as [](#ex-dockerTools-buildImage-runAsRoot), but uses `extraCommands` instead of `runAsRoot`.
320 Note that with `extraCommands`, we can't directly reference `/` and must create files and directories as if we were already on `/`.
323 { dockerTools, buildEnv, hello }:
324 dockerTools.buildImage {
328 copyToRoot = buildEnv {
331 pathsToLink = [ "/bin" ];
336 echo "some content" > my-file
340 Cmd = [ "/bin/hello" ];
341 WorkingDir = "/data";
347 :::{.example #ex-dockerTools-buildImage-creatednow}
348 # Building a Docker image with a creation date set to the current time
350 Note that using a value of `"now"` in the `created` attribute will break reproducibility.
353 { dockerTools, buildEnv, hello }:
354 dockerTools.buildImage {
360 copyToRoot = buildEnv {
363 pathsToLink = [ "/bin" ];
366 config.Cmd = [ "/bin/hello" ];
370 After importing the generated repository tarball with Docker, its CLI will display a reasonable date and sort the images as expected:
374 REPOSITORY TAG IMAGE ID CREATED SIZE
375 hello latest de2bf4786de6 About a minute ago 25.2MB
379 ## buildLayeredImage {#ssec-pkgs-dockerTools-buildLayeredImage}
381 `buildLayeredImage` uses [`streamLayeredImage`](#ssec-pkgs-dockerTools-streamLayeredImage) underneath to build a compressed Docker-compatible repository tarball.
382 Basically, `buildLayeredImage` runs the script created by `streamLayeredImage` to save the compressed image in the Nix store.
383 `buildLayeredImage` supports the same options as `streamLayeredImage`, see [`streamLayeredImage`](#ssec-pkgs-dockerTools-streamLayeredImage) for details.
386 Despite the similar name, [`buildImage`](#ssec-pkgs-dockerTools-buildImage) works completely differently from `buildLayeredImage` and `streamLayeredImage`.
388 Even though some of the arguments may seem related, they cannot be interchanged.
391 You can load the result of this function in Docker with `docker image load`.
392 See [](#ex-dockerTools-buildLayeredImage-hello) to see how to do that.
394 ### Examples {#ssec-pkgs-dockerTools-buildLayeredImage-examples}
396 :::{.example #ex-dockerTools-buildLayeredImage-hello}
397 # Building a layered Docker image
399 The following package builds a layered Docker image that runs the `hello` executable from the `hello` package.
400 The Docker image will have name `hello` and tag `latest`.
403 { dockerTools, hello }:
404 dockerTools.buildLayeredImage {
408 contents = [ hello ];
410 config.Cmd = [ "/bin/hello" ];
414 The result of building this package is a `.tar.gz` file that can be loaded into Docker:
418 (some output removed for clarity)
419 building '/nix/store/bk8bnrbw10nq7p8pvcmdr0qf57y6scha-hello.tar.gz.drv'...
420 No 'fromImage' provided
421 Creating layer 1 from paths: ['/nix/store/i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1']
422 Creating layer 2 from paths: ['/nix/store/ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4']
423 Creating layer 3 from paths: ['/nix/store/ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc']
424 Creating layer 4 from paths: ['/nix/store/9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27']
425 Creating layer 5 from paths: ['/nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1']
426 Creating layer 6 with customisation...
429 /nix/store/hxcz7snvw7f8rzhbh6mv8jq39d992905-hello.tar.gz
431 $ docker image load -i /nix/store/hxcz7snvw7f8rzhbh6mv8jq39d992905-hello.tar.gz
432 (some output removed for clarity)
433 Loaded image: hello:latest
437 ## streamLayeredImage {#ssec-pkgs-dockerTools-streamLayeredImage}
439 `streamLayeredImage` builds a **script** which, when run, will stream to stdout a Docker-compatible repository tarball containing a single image, using multiple layers to improve sharing between images.
440 This means that `streamLayeredImage` does not output an image into the Nix store, but only a script that builds the image, saving on IO and disk/cache space, particularly with large images.
442 You can load the result of this function in Docker with `docker image load`.
443 See [](#ex-dockerTools-streamLayeredImage-hello) to see how to do that.
445 For this function, you specify a [store path](https://nixos.org/manual/nix/stable/store/store-path) or a list of store paths to be added to the image, and the functions will automatically include any dependencies of those paths in the image.
446 The function will attempt to create one layer per object in the Nix store that needs to be added to the image.
447 In case there are more objects to include than available layers, the function will put the most ["popular"](https://github.com/NixOS/nixpkgs/tree/release-23.11/pkgs/build-support/references-by-popularity) objects in their own layers, and group all remaining objects into a single layer.
449 An additional layer will be created with symlinks to the store paths you specified to be included in the image.
450 These symlinks are built with [`symlinkJoin`](#trivial-builder-symlinkJoin), so they will be included in the root of the image.
451 See [](#ex-dockerTools-streamLayeredImage-exploringlayers) to understand how these symlinks are laid out in the generated image.
453 `streamLayeredImage` allows scripts to be run when creating the additional layer with symlinks, allowing custom behaviour to affect the final results of the image (see the documentation of the `extraCommands` and `fakeRootCommands` attributes).
455 The resulting repository tarball will list a single image as specified by the `name` and `tag` attributes.
456 By default, that image will use a static creation date (see documentation for the `created` and `mtime` attributes).
457 This allows the function to produce reproducible images.
459 ### Inputs {#ssec-pkgs-dockerTools-streamLayeredImage-inputs}
461 `streamLayeredImage` expects one argument with the following attributes:
465 : The name of the generated image.
467 `tag` (String or Null; _optional_)
469 : Tag of the generated image.
470 If `null`, the hash of the nix derivation will be used as the tag.
472 _Default value:_ `null`.
474 `fromImage`(Path or Null; _optional_)
476 : The repository tarball of an image to be used as the base for the generated image.
477 It must be a valid Docker image, such as one exported by `docker image save`, or another image built with the `dockerTools` utility functions.
478 This can be seen as an equivalent of `FROM fromImage` in a `Dockerfile`.
479 A value of `null` can be seen as an equivalent of `FROM scratch`.
481 If specified, the created layers will be appended to the layers defined in the base image.
483 _Default value:_ `null`.
485 `contents` (Path or List of Paths; _optional_) []{#dockerTools-buildLayeredImage-arg-contents}
487 : Directories whose contents will be added to the generated image.
488 Things that coerce to paths (e.g. a derivation) can also be used.
489 This can be seen as an equivalent of `ADD contents/ /` in a `Dockerfile`.
491 All the contents specified by `contents` will be added as a final layer in the generated image.
492 They will be added as links to the actual files (e.g. links to the store paths).
493 The actual files will be added in previous layers.
495 _Default value:_ `[]`
497 `config` (Attribute Set or Null; _optional_) []{#dockerTools-buildLayeredImage-arg-config}
499 : Used to specify the configuration of the containers that will be started off the generated image.
500 Must be an attribute set, with each attribute as listed in the [Docker Image Specification v1.3.0](https://github.com/moby/moby/blob/46f7ab808b9504d735d600e259ca0723f76fb164/image/spec/spec.md#image-json-field-descriptions).
502 If any packages are used directly in `config`, they will be automatically included in the generated image.
503 See [](#ex-dockerTools-streamLayeredImage-configclosure) for an example.
505 _Default value:_ `null`.
507 `architecture` (String; _optional_)
509 : Used to specify the image architecture.
510 This is useful for multi-architecture builds that don't need cross compiling.
511 If specified, its value should follow the [OCI Image Configuration Specification](https://github.com/opencontainers/image-spec/blob/main/config.md#properties), which should still be compatible with Docker.
512 According to the linked specification, all possible values for `$GOARCH` in [the Go docs](https://go.dev/doc/install/source#environment) should be valid, but will commonly be one of `386`, `amd64`, `arm`, or `arm64`.
514 _Default value:_ the same value from `pkgs.go.GOARCH`.
516 `created` (String; _optional_)
518 : Specifies the time of creation of the generated image.
519 This date will be used for the image metadata.
520 This should be either a date and time formatted according to [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) or `"now"`, in which case the current date will be used.
523 Using `"now"` means that the generated image will not be reproducible anymore (because the date will always change whenever it's built).
526 _Default value:_ `"1970-01-01T00:00:01Z"`.
528 `mtime` (String; _optional_)
530 : Specifies the time used for the modification timestamp of files within the layers of the generated image.
531 This should be either a date and time formatted according to [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) or `"now"`, in which case the current date will be used.
534 Using a non-constant date will cause built layers to have a different hash each time, preventing deduplication.
535 Using `"now"` also means that the generated image will not be reproducible anymore (because the date will always change whenever it's built).
538 _Default value:_ `"1970-01-01T00:00:01Z"`.
540 `uid` (Number; _optional_) []{#dockerTools-buildLayeredImage-arg-uid}
541 `gid` (Number; _optional_) []{#dockerTools-buildLayeredImage-arg-gid}
542 `uname` (String; _optional_) []{#dockerTools-buildLayeredImage-arg-uname}
543 `gname` (String; _optional_) []{#dockerTools-buildLayeredImage-arg-gname}
545 : Credentials for Nix store ownership.
546 Can be overridden to e.g. `1000` / `1000` / `"user"` / `"user"` to enable building a container where Nix can be used as an unprivileged user in single-user mode.
548 _Default value:_ `0` / `0` / `"root"` / `"root"`
550 `maxLayers` (Number; _optional_) []{#dockerTools-buildLayeredImage-arg-maxLayers}
552 : The maximum number of layers that will be used by the generated image.
553 If a `fromImage` was specified, the number of layers used by `fromImage` will be subtracted from `maxLayers` to ensure that the image generated will have at most `maxLayers`.
556 Depending on the tool/runtime where the image will be used, there might be a limit to the number of layers that an image can have.
557 For Docker, see [this issue on GitHub](https://github.com/docker/docs/issues/8230).
560 _Default value:_ 100.
562 `extraCommands` (String; _optional_)
564 : A bash script that will run in the context of the layer created with the contents specified by `contents`.
565 At the moment this script runs, only the contents directly specified by `contents` will be available as links.
567 _Default value:_ `""`.
569 `fakeRootCommands` (String; _optional_)
571 : A bash script that will run in the context of the layer created with the contents specified by `contents`.
572 During the process to generate that layer, the script in `extraCommands` will be run first, if specified.
573 After that, a {manpage}`fakeroot(1)` environment will be entered.
574 The script specified in `fakeRootCommands` runs inside the fakeroot environment, and the layer is then generated from the view of the files inside the fakeroot environment.
576 This is useful to change the owners of the files in the layer (by running `chown`, for example), or performing any other privileged operations related to file manipulation (by default, all files in the layer will be owned by root, and the build environment doesn't have enough privileges to directly perform privileged operations on these files).
578 For more details, see the manpage for {manpage}`fakeroot(1)`.
581 Due to how fakeroot works, static binaries cannot perform privileged file operations in `fakeRootCommands`, unless `enableFakechroot` is set to `true`.
584 _Default value:_ `""`.
586 `enableFakechroot` (Boolean; _optional_)
588 : By default, the script specified in `fakeRootCommands` only runs inside a fakeroot environment.
589 If `enableFakechroot` is `true`, a more complete chroot environment will be created using [`proot`](https://proot-me.github.io/) before running the script in `fakeRootCommands`.
590 Files in the Nix store will be available.
591 This allows scripts that perform installation in `/` to work as expected.
592 This can be seen as an equivalent of `RUN ...` in a `Dockerfile`.
594 _Default value:_ `false`
596 `includeStorePaths` (Boolean; _optional_)
598 : The files specified in `contents` are put into layers in the generated image.
599 If `includeStorePaths` is `false`, the actual files will not be included in the generated image, and only links to them will be added instead.
600 It is **not recommended** to set this to `false` unless you have other tooling to insert the store paths via other means (such as bind mounting the host store) when running containers with the generated image.
601 If you don't provide any extra tooling, the generated image won't run properly.
603 See [](#ex-dockerTools-streamLayeredImage-exploringlayers) to understand the impact of setting `includeStorePaths` to `false`.
605 _Default value:_ `true`
607 `includeNixDB` (Boolean; _optional_)
609 : Populate the nix database in the image with the dependencies of `copyToRoot`.
610 The main purpose is to be able to use nix commands in the container.
613 Be careful since this doesn't work well in combination with `fromImage`. In particular, in a multi-layered image, only the Nix paths from the lower image will be in the database.
615 This also neglects to register the store paths that are pulled into the image as a dependency of one of the other values, but aren't a dependency of `copyToRoot`.
618 _Default value:_ `false`.
620 `passthru` (Attribute Set; _optional_)
622 : Use this to pass any attributes as [`passthru`](#chap-passthru) for the resulting derivation.
624 _Default value:_ `{}`
626 ### Passthru outputs {#ssec-pkgs-dockerTools-streamLayeredImage-passthru-outputs}
628 `streamLayeredImage` also defines its own [`passthru`](#chap-passthru) attributes:
632 : The tag of the generated image.
633 This is useful if no tag was specified in the attributes of the argument to the function, because an automatic tag will be used instead.
634 `imageTag` allows you to retrieve the value of the tag used in this case.
636 ### Examples {#ssec-pkgs-dockerTools-streamLayeredImage-examples}
638 :::{.example #ex-dockerTools-streamLayeredImage-hello}
639 # Streaming a layered Docker image
641 The following package builds a **script** which, when run, will stream a layered Docker image that runs the `hello` executable from the `hello` package.
642 The Docker image will have name `hello` and tag `latest`.
645 { dockerTools, hello }:
646 dockerTools.streamLayeredImage {
650 contents = [ hello ];
652 config.Cmd = [ "/bin/hello" ];
656 The result of building this package is a script.
657 Running this script and piping it into `docker image load` gives you the same image that was built in [](#ex-dockerTools-buildLayeredImage-hello).
658 Note that in this case, the image is never added to the Nix store, but instead streamed directly into Docker.
662 (output removed for clarity)
663 /nix/store/wsz2xl8ckxnlb769irvq6jv1280dfvxd-stream-hello
665 $ /nix/store/wsz2xl8ckxnlb769irvq6jv1280dfvxd-stream-hello | docker image load
666 No 'fromImage' provided
667 Creating layer 1 from paths: ['/nix/store/i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1']
668 Creating layer 2 from paths: ['/nix/store/ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4']
669 Creating layer 3 from paths: ['/nix/store/ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc']
670 Creating layer 4 from paths: ['/nix/store/9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27']
671 Creating layer 5 from paths: ['/nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1']
672 Creating layer 6 with customisation...
675 (some output removed for clarity)
676 Loaded image: hello:latest
680 :::{.example #ex-dockerTools-streamLayeredImage-exploringlayers}
681 # Exploring the layers in an image built with `streamLayeredImage`
683 Assume the following package, which builds a layered Docker image with the `hello` package.
686 { dockerTools, hello }:
687 dockerTools.streamLayeredImage {
689 contents = [ hello ];
693 The `hello` package depends on 4 other packages:
696 $ nix-store --query -R $(nix-build -A hello)
697 /nix/store/i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1
698 /nix/store/ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4
699 /nix/store/ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc
700 /nix/store/9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27
701 /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1
704 This means that all these packages will be included in the image generated by `streamLayeredImage`.
705 It will put each package in its own layer, for a total of 5 layers with actual files in them.
706 A final layer will be created only with symlinks for the `hello` package.
708 The image generated will have the following directory structure (some directories were collapsed for readability):
712 │ └── hello → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/bin/hello
715 │ ├─⊕ 9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27
716 │ ├─⊕ i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1
717 │ ├─⊕ ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4
718 │ ├─⊕ ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc
719 │ └─⊕ zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1
722 │ └── hello.info → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/info/hello.info
726 └── hello.1.gz → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/man/man1/hello.1.gz
729 Each of the packages in `/nix/store` comes from a layer in the image.
730 The final layer adds the `/bin` and `/share` directories, but they only contain links to the actual files in `/nix/store`.
732 If our package sets `includeStorePaths` to `false`, we'll end up with only the final layer with the links, but the actual files won't exist in the image:
735 { dockerTools, hello }:
736 dockerTools.streamLayeredImage {
738 contents = [ hello ];
739 includeStorePaths = false;
743 After building this package, the image will have the following directory structure:
747 │ └── hello → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/bin/hello
750 │ └── hello.info → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/info/hello.info
754 └── hello.1.gz → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/man/man1/hello.1.gz
757 Note how the links point to paths in `/nix/store`, but they're not included in the image itself.
758 This is why you need extra tooling when using `includeStorePaths`:
759 a container created from such image won't find any of the files it needs to run otherwise.
762 ::: {.example #ex-dockerTools-streamLayeredImage-configclosure}
763 # Building a layered Docker image with packages directly in `config`
765 The closure of `config` is automatically included in the generated image.
766 The following package shows a more compact way to create the same output generated in [](#ex-dockerTools-streamLayeredImage-hello).
769 { dockerTools, hello, lib }:
770 dockerTools.streamLayeredImage {
773 config.Cmd = [ "${lib.getExe hello}" ];
778 []{#ssec-pkgs-dockerTools-fetchFromRegistry}
779 ## pullImage {#ssec-pkgs-dockerTools-pullImage}
781 This function is similar to the `docker image pull` command, which means it can be used to pull a Docker image from a registry that implements the [Docker Registry HTTP API V2](https://distribution.github.io/distribution/spec/api/).
782 By default, the `docker.io` registry is used.
784 The image will be downloaded as an uncompressed Docker-compatible repository tarball, which is suitable for use with other `dockerTools` functions such as [`buildImage`](#ssec-pkgs-dockerTools-buildImage), [`buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage), and [`streamLayeredImage`](#ssec-pkgs-dockerTools-streamLayeredImage).
786 This function requires two different types of hashes/digests to be specified:
788 - One of them is used to identify a unique image within the registry (see the documentation for the `imageDigest` attribute).
789 - The other is used by Nix to ensure the contents of the output haven't changed (see the documentation for the `sha256` attribute).
791 Both hashes are required because they must uniquely identify some content in two completely different systems (the Docker registry and the Nix store), but their values will not be the same.
792 See [](#ex-dockerTools-pullImage-nixprefetchdocker) for a tool that can help gather these values.
794 ### Inputs {#ssec-pkgs-dockerTools-pullImage-inputs}
796 `pullImage` expects a single argument with the following attributes:
800 : Specifies the name of the image to be downloaded, as well as the registry endpoint.
801 By default, the `docker.io` registry is used.
802 To specify a different registry, prepend the endpoint to `imageName`, separated by a slash (`/`).
803 See [](#ex-dockerTools-pullImage-differentregistry) for how to do that.
805 `imageDigest` (String)
807 : Specifies the digest of the image to be downloaded.
810 **Why can't I specify a tag to pull from, and have to use a digest instead?**
812 Tags are often updated to point to different image contents.
813 The most common example is the `latest` tag, which is usually updated whenever a newer image version is available.
815 An image tag isn't enough to guarantee the contents of an image won't change, but a digest guarantees this.
816 Providing a digest helps ensure that you will still be able to build the same Nix code and get the same output even if newer versions of an image are released.
821 : The hash of the image after it is downloaded.
822 Internally, this is passed to the [`outputHash`](https://nixos.org/manual/nix/stable/language/advanced-attributes#adv-attr-outputHash) attribute of the resulting derivation.
823 This is needed to provide a guarantee to Nix that the contents of the image haven't changed, because Nix doesn't support the value in `imageDigest`.
825 `finalImageName` (String; _optional_)
827 : Specifies the name that will be used for the image after it has been downloaded.
828 This only applies after the image is downloaded, and is not used to identify the image to be downloaded in the registry.
829 Use `imageName` for that instead.
831 _Default value:_ the same value specified in `imageName`.
833 `finalImageTag` (String; _optional_)
835 : Specifies the tag that will be used for the image after it has been downloaded.
836 This only applies after the image is downloaded, and is not used to identify the image to be downloaded in the registry.
838 _Default value:_ `"latest"`.
840 `os` (String; _optional_)
842 : Specifies the operating system of the image to pull.
843 If specified, its value should follow the [OCI Image Configuration Specification](https://github.com/opencontainers/image-spec/blob/main/config.md#properties), which should still be compatible with Docker.
844 According to the linked specification, all possible values for `$GOOS` in [the Go docs](https://go.dev/doc/install/source#environment) should be valid, but will commonly be one of `darwin` or `linux`.
846 _Default value:_ `"linux"`.
848 `arch` (String; _optional_)
850 : Specifies the architecture of the image to pull.
851 If specified, its value should follow the [OCI Image Configuration Specification](https://github.com/opencontainers/image-spec/blob/main/config.md#properties), which should still be compatible with Docker.
852 According to the linked specification, all possible values for `$GOARCH` in [the Go docs](https://go.dev/doc/install/source#environment) should be valid, but will commonly be one of `386`, `amd64`, `arm`, or `arm64`.
854 _Default value:_ the same value from `pkgs.go.GOARCH`.
856 `tlsVerify` (Boolean; _optional_)
858 : Used to enable or disable HTTPS and TLS certificate verification when communicating with the chosen Docker registry.
859 Setting this to `false` will make `pullImage` connect to the registry through HTTP.
861 _Default value:_ `true`.
863 `name` (String; _optional_)
865 : The name used for the output in the Nix store path.
867 _Default value:_ a value derived from `finalImageName` and `finalImageTag`, with some symbols replaced.
868 It is recommended to treat the default as an opaque value.
870 ### Examples {#ssec-pkgs-dockerTools-pullImage-examples}
872 ::: {.example #ex-dockerTools-pullImage-niximage}
873 # Pulling the nixos/nix Docker image from the default registry
875 This example pulls the [`nixos/nix` image](https://hub.docker.com/r/nixos/nix) and saves it in the Nix store.
879 dockerTools.pullImage {
880 imageName = "nixos/nix";
881 imageDigest = "sha256:b8ea88f763f33dfda2317b55eeda3b1a4006692ee29e60ee54ccf6d07348c598";
882 finalImageName = "nix";
883 finalImageTag = "2.19.3";
884 sha256 = "zRwlQs1FiKrvHPaf8vWOR/Tlp1C5eLn1d9pE4BZg3oA=";
889 ::: {.example #ex-dockerTools-pullImage-differentregistry}
890 # Pulling the nixos/nix Docker image from a specific registry
892 This example pulls the [`coreos/etcd` image](https://quay.io/repository/coreos/etcd) from the `quay.io` registry.
896 dockerTools.pullImage {
897 imageName = "quay.io/coreos/etcd";
898 imageDigest = "sha256:24a23053f29266fb2731ebea27f915bb0fb2ae1ea87d42d890fe4e44f2e27c5d";
899 finalImageName = "etcd";
900 finalImageTag = "v3.5.11";
901 sha256 = "Myw+85f2/EVRyMB3axECdmQ5eh9p1q77FWYKy8YpRWU=";
906 ::: {.example #ex-dockerTools-pullImage-nixprefetchdocker}
907 # Finding the digest and hash values to use for `dockerTools.pullImage`
909 Since [`dockerTools.pullImage`](#ssec-pkgs-dockerTools-pullImage) requires two different hashes, one can run the `nix-prefetch-docker` tool to find out the values for the hashes.
910 The tool outputs some text for an attribute set which you can pass directly to `pullImage`.
913 $ nix run nixpkgs#nix-prefetch-docker -- --image-name nixos/nix --image-tag 2.19.3 --arch amd64 --os linux
914 (some output removed for clarity)
915 Writing manifest to image destination
916 -> ImageName: nixos/nix
917 -> ImageDigest: sha256:498fa2d7f2b5cb3891a4edf20f3a8f8496e70865099ba72540494cd3e2942634
918 -> FinalImageName: nixos/nix
919 -> FinalImageTag: latest
920 -> ImagePath: /nix/store/4mxy9mn6978zkvlc670g5703nijsqc95-docker-image-nixos-nix-latest.tar
921 -> ImageHash: 1q6cf2pdrasa34zz0jw7pbs6lvv52rq2aibgxccbwcagwkg2qj1q
923 imageName = "nixos/nix";
924 imageDigest = "sha256:498fa2d7f2b5cb3891a4edf20f3a8f8496e70865099ba72540494cd3e2942634";
925 sha256 = "1q6cf2pdrasa34zz0jw7pbs6lvv52rq2aibgxccbwcagwkg2qj1q";
926 finalImageName = "nixos/nix";
927 finalImageTag = "latest";
931 It is important to supply the `--arch` and `--os` arguments to `nix-prefetch-docker` to filter to a single image, in case there are multiple architectures and/or operating systems supported by the image name and tags specified.
932 By default, `nix-prefetch-docker` will set `os` to `linux` and `arch` to `amd64`.
934 Run `nix-prefetch-docker --help` for a list of all supported arguments:
936 $ nix run nixpkgs#nix-prefetch-docker -- --help
937 (output removed for clarity)
941 ## exportImage {#ssec-pkgs-dockerTools-exportImage}
943 This function is similar to the `docker container export` command, which means it can be used to export an image's filesystem as an uncompressed tarball archive.
944 The difference is that `docker container export` is applied to containers, but `dockerTools.exportImage` applies to Docker images.
945 The resulting archive will not contain any image metadata (such as command to run with `docker container run`), only the filesystem contents.
947 You can use this function to import an archive in Docker with `docker image import`.
948 See [](#ex-dockerTools-exportImage-importingDocker) to understand how to do that.
951 `exportImage` works by unpacking the given image inside a VM.
952 Because of this, using this function requires the `kvm` device to be available, see [`system-features`](https://nixos.org/manual/nix/stable/command-ref/conf-file.html#conf-system-features).
955 ### Inputs {#ssec-pkgs-dockerTools-exportImage-inputs}
957 `exportImage` expects an argument with the following attributes:
959 `fromImage` (Attribute Set or String)
961 : The repository tarball of the image whose filesystem will be exported.
962 It must be a valid Docker image, such as one exported by `docker image save`, or another image built with the `dockerTools` utility functions.
964 If `name` is not specified, `fromImage` must be an Attribute Set corresponding to a derivation, i.e. it can't be a path to a tarball.
965 If `name` is specified, `fromImage` can be either an Attribute Set corresponding to a derivation or simply a path to a tarball.
967 See [](#ex-dockerTools-exportImage-naming) and [](#ex-dockerTools-exportImage-fromImagePath) to understand the connection between `fromImage`, `name`, and the name used for the output of `exportImage`.
969 `fromImageName` (String or Null; _optional_)
971 : Used to specify the image within the repository tarball in case it contains multiple images.
972 A value of `null` means that `exportImage` will use the first image available in the repository.
975 This must be used with `fromImageTag`. Using only `fromImageName` without `fromImageTag` will make `exportImage` use the first image available in the repository.
978 _Default value:_ `null`.
980 `fromImageTag` (String or Null; _optional_)
982 : Used to specify the image within the repository tarball in case it contains multiple images.
983 A value of `null` means that `exportImage` will use the first image available in the repository.
986 This must be used with `fromImageName`. Using only `fromImageTag` without `fromImageName` will make `exportImage` use the first image available in the repository
989 _Default value:_ `null`.
991 `diskSize` (Number; _optional_)
993 : Controls the disk size (in megabytes) of the VM used to unpack the image.
995 _Default value:_ 1024.
997 `name` (String; _optional_)
999 : The name used for the output in the Nix store path.
1001 _Default value:_ the value of `fromImage.name`.
1003 ### Examples {#ssec-pkgs-dockerTools-exportImage-examples}
1005 :::{.example #ex-dockerTools-exportImage-hello}
1006 # Exporting a Docker image with `dockerTools.exportImage`
1008 This example first builds a layered image with [`dockerTools.buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage), and then exports its filesystem with `dockerTools.exportImage`.
1011 { dockerTools, hello }:
1012 dockerTools.exportImage {
1014 fromImage = dockerTools.buildLayeredImage {
1016 contents = [ hello ];
1021 When building the package above, we can see the layers of the Docker image being unpacked to produce the final output:
1025 (some output removed for clarity)
1026 Unpacking base image...
1027 From-image name or tag wasn't set. Reading the first ID.
1028 Unpacking layer 5731199219418f175d1580dbca05677e69144425b2d9ecb60f416cd57ca3ca42/layer.tar
1029 tar: Removing leading `/' from member names
1030 Unpacking layer e2897bf34bb78c4a65736510204282d9f7ca258ba048c183d665bd0f3d24c5ec/layer.tar
1031 tar: Removing leading `/' from member names
1032 Unpacking layer 420aa5876dca4128cd5256da7dea0948e30ef5971712f82601718cdb0a6b4cda/layer.tar
1033 tar: Removing leading `/' from member names
1034 Unpacking layer ea5f4e620e7906c8ecbc506b5e6f46420e68d4b842c3303260d5eb621b5942e5/layer.tar
1035 tar: Removing leading `/' from member names
1036 Unpacking layer 65807b9abe8ab753fa97da8fb74a21fcd4725cc51e1b679c7973c97acd47ebcf/layer.tar
1037 tar: Removing leading `/' from member names
1038 Unpacking layer b7da2076b60ebc0ea6824ef641978332b8ac908d47b2d07ff31b9cc362245605/layer.tar
1039 Executing post-mount steps...
1040 Packing raw image...
1041 [ 1.660036] reboot: Power down
1042 /nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello
1045 The following command lists some of the contents of the output to verify that the structure of the archive is as expected:
1048 $ tar --exclude '*/share/*' --exclude 'nix/store/*/*' -tvf /nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello
1049 drwxr-xr-x root/0 0 1979-12-31 16:00 ./
1050 drwxr-xr-x root/0 0 1979-12-31 16:00 ./bin/
1051 lrwxrwxrwx root/0 0 1979-12-31 16:00 ./bin/hello -> /nix/store/h92a9jd0lhhniv2q417hpwszd4jhys7q-hello-2.12.1/bin/hello
1052 dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/
1053 dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/
1054 dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/05zbwhz8a7i2v79r9j21pl6m6cj0xi8k-libunistring-1.1/
1055 dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/ayg5rhjhi9ic73hqw33mjqjxwv59ndym-xgcc-13.2.0-libgcc/
1056 dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/h92a9jd0lhhniv2q417hpwszd4jhys7q-hello-2.12.1/
1057 dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/m59xdgkgnjbk8kk6k6vbxmqnf82mk9s0-libidn2-2.3.4/
1058 dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/p3jshbwxiwifm1py0yq544fmdyy98j8a-glibc-2.38-27/
1059 drwxr-xr-x root/0 0 1979-12-31 16:00 ./share/
1063 :::{.example #ex-dockerTools-exportImage-importingDocker}
1064 # Importing an archive built with `dockerTools.exportImage` in Docker
1066 We will use the same package from [](#ex-dockerTools-exportImage-hello) and import it into Docker.
1069 { dockerTools, hello }:
1070 dockerTools.exportImage {
1072 fromImage = dockerTools.buildLayeredImage {
1074 contents = [ hello ];
1079 Building and importing it into Docker:
1083 (output removed for clarity)
1084 /nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello
1085 $ docker image import /nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello
1086 sha256:1d42dba415e9b298ea0decf6497fbce954de9b4fcb2984f91e307c8fedc1f52f
1088 REPOSITORY TAG IMAGE ID CREATED SIZE
1089 <none> <none> 1d42dba415e9 4 seconds ago 32.6MB
1093 :::{.example #ex-dockerTools-exportImage-naming}
1094 # Exploring output naming with `dockerTools.exportImage`
1096 `exportImage` does not require a `name` attribute if `fromImage` is a derivation, which means that the following works:
1099 { dockerTools, hello }:
1100 dockerTools.exportImage {
1101 fromImage = dockerTools.buildLayeredImage {
1103 contents = [ hello ];
1108 However, since [`dockerTools.buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage)'s output ends with `.tar.gz`, the output of `exportImage` will also end with `.tar.gz`, even though the archive created with `exportImage` is uncompressed:
1112 (output removed for clarity)
1113 /nix/store/by3f40xvc4l6bkis74l0fj4zsy0djgkn-hello.tar.gz
1114 $ file /nix/store/by3f40xvc4l6bkis74l0fj4zsy0djgkn-hello.tar.gz
1115 /nix/store/by3f40xvc4l6bkis74l0fj4zsy0djgkn-hello.tar.gz: POSIX tar archive (GNU)
1118 If the archive was actually compressed, the output of file would've mentioned that fact.
1119 Because of this, it may be important to set a proper `name` attribute when using `exportImage` with other functions from `dockerTools`.
1122 :::{.example #ex-dockerTools-exportImage-fromImagePath}
1123 # Using `dockerTools.exportImage` with a path as `fromImage`
1125 It is possible to use a path as the value of the `fromImage` attribute when calling `dockerTools.exportImage`.
1126 However, when doing so, a `name` attribute **MUST** be specified, or you'll encounter an error when evaluating the Nix code.
1128 For this example, we'll assume a Docker tarball image named `image.tar.gz` exists in the same directory where our package is defined:
1132 dockerTools.exportImage {
1133 name = "filesystem.tar";
1134 fromImage = ./image.tar.gz;
1138 Building this will give us the expected output:
1142 (output removed for clarity)
1143 /nix/store/w13l8h3nlkg0zv56k7rj0ai0l2zlf7ss-filesystem.tar
1146 If you don't specify a `name` attribute, you'll encounter an evaluation error and the package won't build.
1149 ## Environment Helpers {#ssec-pkgs-dockerTools-helpers}
1151 When building Docker images with Nix, you might also want to add certain files that are expected to be available globally by the software you're packaging.
1152 Simple examples are the `env` utility in `/usr/bin/env`, or trusted root TLS/SSL certificates.
1153 Such files will most likely not be included if you're building a Docker image from scratch with Nix, and they might also not be included if you're starting from a Docker image that doesn't include them.
1154 The helpers in this section are packages that provide some of these commonly-needed global files.
1156 Most of these helpers are packages, which means you have to add them to the list of contents to be included in the image (this changes depending on the function you're using to build the image).
1157 [](#ex-dockerTools-helpers-buildImage) and [](#ex-dockerTools-helpers-buildLayeredImage) show how to include these packages on `dockerTools` functions that build an image.
1158 For more details on how that works, see the documentation for the function you're using.
1160 ### usrBinEnv {#sssec-pkgs-dockerTools-helpers-usrBinEnv}
1162 This provides the `env` utility at `/usr/bin/env`.
1163 This is currently implemented by linking to the `env` binary from the `coreutils` package, but is considered an implementation detail that could change in the future.
1165 ### binSh {#sssec-pkgs-dockerTools-helpers-binSh}
1167 This provides a `/bin/sh` link to the `bash` binary from the `bashInteractive` package.
1168 Because of this, it supports cases such as running a command interactively in a container (for example by running `docker container run -it <image_name>`).
1170 ### caCertificates {#sssec-pkgs-dockerTools-helpers-caCertificates}
1172 This adds trusted root TLS/SSL certificates from the `cacert` package in multiple locations in an attempt to be compatible with binaries built for multiple Linux distributions.
1173 The locations currently used are:
1175 - `/etc/ssl/certs/ca-bundle.crt`
1176 - `/etc/ssl/certs/ca-certificates.crt`
1177 - `/etc/pki/tls/certs/ca-bundle.crt`
1179 []{#ssec-pkgs-dockerTools-fakeNss}
1180 ### fakeNss {#sssec-pkgs-dockerTools-helpers-fakeNss}
1182 This is a re-export of the `fakeNss` package from Nixpkgs.
1183 See [](#sec-fakeNss).
1185 ### shadowSetup {#ssec-pkgs-dockerTools-shadowSetup}
1187 This is a string containing a script that sets up files needed for [`shadow`](https://github.com/shadow-maint/shadow) to work (using the `shadow` package from Nixpkgs), and alters `PATH` to make all its utilities available in the same script.
1188 It is intended to be used with other dockerTools functions in attributes that expect scripts.
1189 After the script in `shadowSetup` runs, you'll then be able to add more commands that make use of the utilities in `shadow`, such as adding any extra users and/or groups.
1190 See [](#ex-dockerTools-shadowSetup-buildImage) and [](#ex-dockerTools-shadowSetup-buildLayeredImage) to better understand how to use it.
1192 `shadowSetup` achieves a result similar to [`fakeNss`](#sssec-pkgs-dockerTools-helpers-fakeNss), but only sets up a `root` user with different values for the home directory and the shell to use, in addition to setting up files for [PAM](https://en.wikipedia.org/wiki/Linux_PAM) and a {manpage}`login.defs(5)` file.
1195 Using both `fakeNss` and `shadowSetup` at the same time will either cause your build to break or produce unexpected results.
1196 Use either `fakeNss` or `shadowSetup` depending on your use case, but avoid using both.
1200 When used with [`buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage) or [`streamLayeredImage`](#ssec-pkgs-dockerTools-streamLayeredImage), you will have to set the `enableFakechroot` attribute to `true`, or else the script in `shadowSetup` won't run properly.
1201 See [](#ex-dockerTools-shadowSetup-buildLayeredImage).
1204 ### Examples {#ssec-pkgs-dockerTools-helpers-examples}
1206 :::{.example #ex-dockerTools-helpers-buildImage}
1207 # Using `dockerTools`'s environment helpers with `buildImage`
1209 This example adds the [`binSh`](#sssec-pkgs-dockerTools-helpers-binSh) helper to a basic Docker image built with [`dockerTools.buildImage`](#ssec-pkgs-dockerTools-buildImage).
1210 This helper makes it possible to enter a shell inside the container.
1211 This is the `buildImage` equivalent of [](#ex-dockerTools-helpers-buildLayeredImage).
1214 { dockerTools, hello }:
1215 dockerTools.buildImage {
1216 name = "env-helpers";
1226 After building the image and loading it in Docker, we can create a container based on it and enter a shell inside the container.
1227 This is made possible by `binSh`.
1231 (some output removed for clarity)
1232 /nix/store/2p0i3i04cgjlk71hsn7ll4kxaxxiv4qg-docker-image-env-helpers.tar.gz
1233 $ docker image load -i /nix/store/2p0i3i04cgjlk71hsn7ll4kxaxxiv4qg-docker-image-env-helpers.tar.gz
1234 (output removed for clarity)
1235 $ docker container run --rm -it env-helpers:latest /bin/sh
1237 GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
1238 (rest of output removed for clarity)
1242 :::{.example #ex-dockerTools-helpers-buildLayeredImage}
1243 # Using `dockerTools`'s environment helpers with `buildLayeredImage`
1245 This example adds the [`binSh`](#sssec-pkgs-dockerTools-helpers-binSh) helper to a basic Docker image built with [`dockerTools.buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage).
1246 This helper makes it possible to enter a shell inside the container.
1247 This is the `buildLayeredImage` equivalent of [](#ex-dockerTools-helpers-buildImage).
1250 { dockerTools, hello }:
1251 dockerTools.buildLayeredImage {
1252 name = "env-helpers";
1261 Cmd = [ "/bin/hello" ];
1266 After building the image and loading it in Docker, we can create a container based on it and enter a shell inside the container.
1267 This is made possible by `binSh`.
1271 (some output removed for clarity)
1272 /nix/store/rpf47f4z5b9qr4db4ach9yr4b85hjhxq-env-helpers.tar.gz
1273 $ docker image load -i /nix/store/rpf47f4z5b9qr4db4ach9yr4b85hjhxq-env-helpers.tar.gz
1274 (output removed for clarity)
1275 $ docker container run --rm -it env-helpers:latest /bin/sh
1277 GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu)
1278 (rest of output removed for clarity)
1282 :::{.example #ex-dockerTools-shadowSetup-buildImage}
1283 # Using `dockerTools.shadowSetup` with `dockerTools.buildImage`
1285 This is an example that shows how to use `shadowSetup` with `dockerTools.buildImage`.
1286 Note that the extra script in `runAsRoot` uses `groupadd` and `useradd`, which are binaries provided by the `shadow` package.
1287 These binaries are added to the `PATH` by the `shadowSetup` script, but only for the duration of `runAsRoot`.
1290 { dockerTools, hello }:
1291 dockerTools.buildImage {
1292 name = "shadow-basic";
1295 copyToRoot = [ hello ];
1298 ${dockerTools.shadowSetup}
1300 useradd -r -g hello hello
1302 chown hello:hello /data
1306 Cmd = [ "/bin/hello" ];
1307 WorkingDir = "/data";
1313 :::{.example #ex-dockerTools-shadowSetup-buildLayeredImage}
1314 # Using `dockerTools.shadowSetup` with `dockerTools.buildLayeredImage`
1316 It accomplishes the same thing as [](#ex-dockerTools-shadowSetup-buildImage), but using `buildLayeredImage` instead.
1318 Note that the extra script in `fakeRootCommands` uses `groupadd` and `useradd`, which are binaries provided by the `shadow` package.
1319 These binaries are added to the `PATH` by the `shadowSetup` script, but only for the duration of `fakeRootCommands`.
1322 { dockerTools, hello }:
1323 dockerTools.buildLayeredImage {
1324 name = "shadow-basic";
1327 contents = [ hello ];
1329 fakeRootCommands = ''
1330 ${dockerTools.shadowSetup}
1332 useradd -r -g hello hello
1334 chown hello:hello /data
1336 enableFakechroot = true;
1339 Cmd = [ "/bin/hello" ];
1340 WorkingDir = "/data";
1346 []{#ssec-pkgs-dockerTools-buildNixShellImage-arguments}
1347 ## buildNixShellImage {#ssec-pkgs-dockerTools-buildNixShellImage}
1349 `buildNixShellImage` uses [`streamNixShellImage`](#ssec-pkgs-dockerTools-streamNixShellImage) underneath to build a compressed Docker-compatible repository tarball of an image that sets up an environment similar to that of running `nix-shell` on a derivation.
1350 Basically, `buildNixShellImage` runs the script created by `streamNixShellImage` to save the compressed image in the Nix store.
1352 `buildNixShellImage` supports the same options as `streamNixShellImage`, see [`streamNixShellImage`](#ssec-pkgs-dockerTools-streamNixShellImage) for details.
1354 []{#ssec-pkgs-dockerTools-buildNixShellImage-example}
1355 ### Examples {#ssec-pkgs-dockerTools-buildNixShellImage-examples}
1357 :::{.example #ex-dockerTools-buildNixShellImage-hello}
1358 # Building a Docker image with `buildNixShellImage` with the build environment for the `hello` package
1360 This example shows how to build the `hello` package inside a Docker container built with `buildNixShellImage`.
1361 The Docker image generated will have a name like `hello-<version>-env` and tag `latest`.
1362 This example is the `buildNixShellImage` equivalent of [](#ex-dockerTools-streamNixShellImage-hello).
1365 { dockerTools, hello }:
1366 dockerTools.buildNixShellImage {
1372 The result of building this package is a `.tar.gz` file that can be loaded into Docker:
1376 (some output removed for clarity)
1377 /nix/store/pkj1sgzaz31wl0pbvbg3yp5b3kxndqms-hello-2.12.1-env.tar.gz
1379 $ docker image load -i /nix/store/pkj1sgzaz31wl0pbvbg3yp5b3kxndqms-hello-2.12.1-env.tar.gz
1380 (some output removed for clarity)
1381 Loaded image: hello-2.12.1-env:latest
1384 After starting an interactive container, the derivation can be built by running `buildDerivation`, and the output can be executed as expected:
1387 $ docker container run -it hello-2.12.1-env:latest
1388 [nix-shell:~]$ buildDerivation
1389 Running phase: unpackPhase
1390 unpacking source archive /nix/store/pa10z4ngm0g83kx9mssrqzz30s84vq7k-hello-2.12.1.tar.gz
1391 source root is hello-2.12.1
1392 (some output removed for clarity)
1393 Running phase: fixupPhase
1394 shrinking RPATHs of ELF executables and libraries in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1
1395 shrinking /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin/hello
1396 checking for references to /build/ in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1...
1397 gzipping man pages under /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/share/man/
1398 patching script interpreter paths in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1
1399 stripping (with command strip and flags -S -p) in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin
1401 [nix-shell:~]$ $out/bin/hello
1406 ## streamNixShellImage {#ssec-pkgs-dockerTools-streamNixShellImage}
1408 `streamNixShellImage` builds a **script** which, when run, will stream to stdout a Docker-compatible repository tarball of an image that sets up an environment similar to that of running `nix-shell` on a derivation.
1409 This means that `streamNixShellImage` does not output an image into the Nix store, but only a script that builds the image, saving on IO and disk/cache space, particularly with large images.
1410 See [](#ex-dockerTools-streamNixShellImage-hello) to understand how to load in Docker the image generated by this script.
1412 The environment set up by `streamNixShellImage` somewhat resembles the Nix sandbox typically used by `nix-build`, with a major difference being that access to the internet is allowed.
1413 It also behaves like an interactive `nix-shell`, running things like `shellHook` (see [](#ex-dockerTools-streamNixShellImage-addingShellHook)) and setting an interactive prompt.
1414 If the derivation is buildable (i.e. `nix-build` can be used on it), running `buildDerivation` in the container will build the derivation, with all its outputs being available in the correct `/nix/store` paths, pointed to by the respective environment variables (e.g. `$out`).
1417 The environment in the image doesn't match `nix-shell` or `nix-build` exactly, and this function is known not to work correctly for fixed-output derivations, content-addressed derivations, impure derivations and other special types of derivations.
1420 ### Inputs {#ssec-pkgs-dockerTools-streamNixShellImage-inputs}
1422 `streamNixShellImage` expects one argument with the following attributes:
1424 `drv` (Attribute Set)
1426 : The derivation for which the environment in the image will be set up.
1427 Adding packages to the Docker image is possible by extending the list of `nativeBuildInputs` of this derivation.
1428 See [](#ex-dockerTools-streamNixShellImage-extendingBuildInputs) for how to do that.
1429 Similarly, you can extend the image initialization script by extending `shellHook`.
1430 [](#ex-dockerTools-streamNixShellImage-addingShellHook) shows how to do that.
1432 `name` (String; _optional_)
1434 : The name of the generated image.
1436 _Default value:_ the value of `drv.name + "-env"`.
1438 `tag` (String or Null; _optional_)
1440 : Tag of the generated image.
1441 If `null`, the hash of the nix derivation that builds the Docker image will be used as the tag.
1443 _Default value:_ `null`.
1445 `uid` (Number; _optional_)
1447 : The user ID to run the container as.
1448 This can be seen as a `nixbld` build user.
1450 _Default value:_ 1000.
1452 `gid` (Number; _optional_)
1454 : The group ID to run the container as.
1455 This can be seen as a `nixbld` build group.
1457 _Default value:_ 1000.
1459 `homeDirectory` (String; _optional_)
1461 : The home directory of the user the container is running as.
1463 _Default value:_ `/build`.
1465 `shell` (String; _optional_)
1467 : The path to the `bash` binary to use as the shell.
1468 This shell is started when running the image.
1469 This can be seen as an equivalent of the `NIX_BUILD_SHELL` [environment variable](https://nixos.org/manual/nix/stable/command-ref/nix-shell.html#environment-variables) for {manpage}`nix-shell(1)`.
1471 _Default value:_ the `bash` binary from the `bashInteractive` package.
1473 `command` (String or Null; _optional_)
1475 : If specified, this command will be run in the environment of the derivation in an interactive shell.
1476 A call to `exit` will be added after the command if it is specified, so the shell will exit after it's finished running.
1477 This can be seen as an equivalent of the `--command` option in {manpage}`nix-shell(1)`.
1479 _Default value:_ `null`.
1481 `run` (String or Null; _optional_)
1483 : Similar to the `command` attribute, but runs the command in a non-interactive shell instead.
1484 A call to `exit` will be added after the command if it is specified, so the shell will exit after it's finished running.
1485 This can be seen as an equivalent of the `--run` option in {manpage}`nix-shell(1)`.
1487 _Default value:_ `null`.
1489 ### Examples {#ssec-pkgs-dockerTools-streamNixShellImage-examples}
1491 :::{.example #ex-dockerTools-streamNixShellImage-hello}
1492 # Building a Docker image with `streamNixShellImage` with the build environment for the `hello` package
1494 This example shows how to build the `hello` package inside a Docker container built with `streamNixShellImage`.
1495 The Docker image generated will have a name like `hello-<version>-env` and tag `latest`.
1496 This example is the `streamNixShellImage` equivalent of [](#ex-dockerTools-buildNixShellImage-hello).
1499 { dockerTools, hello }:
1500 dockerTools.streamNixShellImage {
1506 The result of building this package is a script.
1507 Running this script and piping it into `docker image load` gives you the same image that was built in [](#ex-dockerTools-buildNixShellImage-hello).
1511 (some output removed for clarity)
1512 /nix/store/8vhznpz2frqazxnd8pgdvf38jscdypax-stream-hello-2.12.1-env
1514 $ /nix/store/8vhznpz2frqazxnd8pgdvf38jscdypax-stream-hello-2.12.1-env | docker image load
1515 (some output removed for clarity)
1516 Loaded image: hello-2.12.1-env:latest
1519 After starting an interactive container, the derivation can be built by running `buildDerivation`, and the output can be executed as expected:
1522 $ docker container run -it hello-2.12.1-env:latest
1523 [nix-shell:~]$ buildDerivation
1524 Running phase: unpackPhase
1525 unpacking source archive /nix/store/pa10z4ngm0g83kx9mssrqzz30s84vq7k-hello-2.12.1.tar.gz
1526 source root is hello-2.12.1
1527 (some output removed for clarity)
1528 Running phase: fixupPhase
1529 shrinking RPATHs of ELF executables and libraries in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1
1530 shrinking /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin/hello
1531 checking for references to /build/ in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1...
1532 gzipping man pages under /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/share/man/
1533 patching script interpreter paths in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1
1534 stripping (with command strip and flags -S -p) in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin
1536 [nix-shell:~]$ $out/bin/hello
1541 :::{.example #ex-dockerTools-streamNixShellImage-extendingBuildInputs}
1542 # Adding extra packages to a Docker image built with `streamNixShellImage`
1544 This example shows how to add extra packages to an image built with `streamNixShellImage`.
1545 In this case, we'll add the `cowsay` package.
1546 The Docker image generated will have a name like `hello-<version>-env` and tag `latest`.
1547 This example uses [](#ex-dockerTools-streamNixShellImage-hello) as a starting point.
1550 { dockerTools, cowsay, hello }:
1551 dockerTools.streamNixShellImage {
1553 drv = hello.overrideAttrs (old: {
1554 nativeBuildInputs = old.nativeBuildInputs or [] ++ [
1561 The result of building this package is a script which can be run and piped into `docker image load` to load the generated image.
1565 (some output removed for clarity)
1566 /nix/store/h5abh0vljgzg381lna922gqknx6yc0v7-stream-hello-2.12.1-env
1568 $ /nix/store/h5abh0vljgzg381lna922gqknx6yc0v7-stream-hello-2.12.1-env | docker image load
1569 (some output removed for clarity)
1570 Loaded image: hello-2.12.1-env:latest
1573 After starting an interactive container, we can verify the extra package is available by running `cowsay`:
1576 $ docker container run -it hello-2.12.1-env:latest
1577 [nix-shell:~]$ cowsay "Hello, world!"
1589 :::{.example #ex-dockerTools-streamNixShellImage-addingShellHook}
1590 # Adding a `shellHook` to a Docker image built with `streamNixShellImage`
1592 This example shows how to add a `shellHook` command to an image built with `streamNixShellImage`.
1593 In this case, we'll simply output the string `Hello, world!`.
1594 The Docker image generated will have a name like `hello-<version>-env` and tag `latest`.
1595 This example uses [](#ex-dockerTools-streamNixShellImage-hello) as a starting point.
1598 { dockerTools, hello }:
1599 dockerTools.streamNixShellImage {
1601 drv = hello.overrideAttrs (old: {
1603 ${old.shellHook or ""}
1604 echo "Hello, world!"
1610 The result of building this package is a script which can be run and piped into `docker image load` to load the generated image.
1614 (some output removed for clarity)
1615 /nix/store/iz4dhdvgzazl5vrgyz719iwjzjy6xlx1-stream-hello-2.12.1-env
1617 $ /nix/store/iz4dhdvgzazl5vrgyz719iwjzjy6xlx1-stream-hello-2.12.1-env | docker image load
1618 (some output removed for clarity)
1619 Loaded image: hello-2.12.1-env:latest
1622 After starting an interactive container, we can see the result of the `shellHook`:
1625 $ docker container run -it hello-2.12.1-env:latest