1# pkgs.dockerTools {#sec-pkgs-dockerTools} 2 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). 4Docker itself is not used to perform any of the operations done by these functions. 5 6## buildImage {#ssec-pkgs-dockerTools-buildImage} 7 8This function builds a Docker-compatible repository tarball containing a single image. 9As such, the result is suitable for being loaded in Docker with `docker image load` (see [](#ex-dockerTools-buildImage) for how to do this). 10 11This function will create a single layer for all files (and dependencies) that are specified in its argument. 12Only new dependencies that are not already in the existing layers will be copied. 13If 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. 14 15This 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). 16 17The resulting repository tarball will list a single image as specified by the `name` and `tag` attributes. 18By default, that image will use a static creation date (see documentation for the `created` attribute). 19This allows `buildImage` to produce reproducible images. 20 21:::{.tip} 22When 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. 23 24If 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. 25Similarly, 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. 26::: 27 28### Inputs {#ssec-pkgs-dockerTools-buildImage-inputs} 29 30`buildImage` expects an argument with the following attributes: 31 32`name` (String) 33 34: The name of the generated image. 35 36`tag` (String or Null; _optional_) 37 38: Tag of the generated image. 39 If `null`, the hash of the nix derivation will be used as the tag. 40 41 _Default value:_ `null`. 42 43`fromImage` (Path or Null; _optional_) 44 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`. 49 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`. 52 53 :::{.note} 54 Only **Env** configuration is inherited from the base image. 55 ::: 56 57 _Default value:_ `null`. 58 59`fromImageName` (String or Null; _optional_) 60 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. 63 64 :::{.note} 65 This must be used with `fromImageTag`. Using only `fromImageName` without `fromImageTag` will make `buildImage` use the first image available in the repository. 66 ::: 67 68 _Default value:_ `null`. 69 70`fromImageTag` (String or Null; _optional_) 71 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. 74 75 :::{.note} 76 This must be used with `fromImageName`. Using only `fromImageTag` without `fromImageName` will make `buildImage` use the first image available in the repository 77 ::: 78 79 _Default value:_ `null`. 80 81`copyToRoot` (Path, List of Paths, or Null; _optional_) 82 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`. 86 87 _Default value:_ `null`. 88 89`keepContentsDirlinks` (Boolean; _optional_) 90 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`. 94 95 _Default value:_ `false`. 96 97`runAsRoot` (String or Null; _optional_) 98 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. 103 104 See [](#ex-dockerTools-buildImage-runAsRoot) for how to work with this attribute. 105 106 :::{.caution} 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. 110 ::: 111 112 :::{.note} 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. 115 ::: 116 117 _Default value:_ `null`. 118 119`extraCommands` (String; _optional_) 120 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`. 125 126 See [](#ex-dockerTools-buildImage-extraCommands) for how to work with this attribute, and subtle differences compared to `runAsRoot`. 127 128 _Default value:_ `""`. 129 130`config` (Attribute Set or Null; _optional_) 131 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). 134 135 _Default value:_ `null`. 136 137`architecture` (String; _optional_) 138 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`. 143 144 _Default value:_ the same value from `pkgs.go.GOARCH`. 145 146`diskSize` (Number; _optional_) 147 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`. 150 151 _Default value:_ 1024. 152 153`buildVMMemorySize` (Number; _optional_) 154 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`. 157 158 _Default value:_ 512. 159 160`created` (String; _optional_) 161 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. 164 165 See [](#ex-dockerTools-buildImage-creatednow) for how to use `"now"`. 166 167 :::{.caution} 168 Using `"now"` means that the generated image will not be reproducible anymore (because the date will always change whenever it's built). 169 ::: 170 171 _Default value:_ `"1970-01-01T00:00:01Z"`. 172 173`uid` (Number; _optional_) 174 175: The uid of the user that will own the files packed in the new layer built by `buildImage`. 176 177 _Default value:_ 0. 178 179`gid` (Number; _optional_) 180 181: The gid of the group that will own the files packed in the new layer built by `buildImage`. 182 183 _Default value:_ 0. 184 185`compressor` (String; _optional_) 186 187: Selects the algorithm used to compress the image. 188 189 _Default value:_ `"gz"`.\ 190 _Possible values:_ `"none"`, `"gz"`, `"zstd"`. 191 192`includeNixDB` (Boolean; _optional_) 193 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. 196 197 :::{.caution} 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. 199 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`. 201 ::: 202 203 _Default value:_ `false`. 204 205`contents` **DEPRECATED** 206 207: This attribute is deprecated, and users are encouraged to use `copyToRoot` instead. 208 209### Passthru outputs {#ssec-pkgs-dockerTools-buildImage-passthru-outputs} 210 211`buildImage` defines a few [`passthru`](#chap-passthru) attributes: 212 213`buildArgs` (Attribute Set) 214 215: The argument passed to `buildImage` itself. 216 This allows you to inspect all attributes specified in the argument, as described above. 217 218`layer` (Attribute Set) 219 220: The derivation with the layer created by `buildImage`. 221 This allows easier inspection of the contents added by `buildImage` in the generated image. 222 223`imageTag` (String) 224 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. 228 229### Examples {#ssec-pkgs-dockerTools-buildImage-examples} 230 231:::{.example #ex-dockerTools-buildImage} 232# Building a Docker image 233 234The following package builds a Docker image that runs the `redis-server` executable from the `redis` package. 235The Docker image will have name `redis` and tag `latest`. 236 237```nix 238{ 239 dockerTools, 240 buildEnv, 241 redis, 242}: 243dockerTools.buildImage { 244 name = "redis"; 245 tag = "latest"; 246 247 copyToRoot = buildEnv { 248 name = "image-root"; 249 paths = [ redis ]; 250 pathsToLink = [ "/bin" ]; 251 }; 252 253 runAsRoot = '' 254 mkdir -p /data 255 ''; 256 257 config = { 258 Cmd = [ "/bin/redis-server" ]; 259 WorkingDir = "/data"; 260 Volumes = { 261 "/data" = { }; 262 }; 263 }; 264} 265``` 266 267The result of building this package is a `.tar.gz` file that can be loaded into Docker: 268 269```shell 270$ nix-build 271(some output removed for clarity) 272building '/nix/store/yw0adm4wpsw1w6j4fb5hy25b3arr9s1v-docker-image-redis.tar.gz.drv'... 273Adding layer... 274tar: Removing leading `/' from member names 275Adding meta... 276Cooking the image... 277Finished. 278/nix/store/p4dsg62inh9d2ksy3c7bv58xa851dasr-docker-image-redis.tar.gz 279 280$ docker image load -i /nix/store/p4dsg62inh9d2ksy3c7bv58xa851dasr-docker-image-redis.tar.gz 281(some output removed for clarity) 282Loaded image: redis:latest 283``` 284::: 285 286:::{.example #ex-dockerTools-buildImage-runAsRoot} 287# Building a Docker image with `runAsRoot` 288 289The following package builds a Docker image with the `hello` executable from the `hello` package. 290It uses `runAsRoot` to create a directory and a file inside the image. 291 292This works the same as [](#ex-dockerTools-buildImage-extraCommands), but uses `runAsRoot` instead of `extraCommands`. 293 294```nix 295{ 296 dockerTools, 297 buildEnv, 298 hello, 299}: 300dockerTools.buildImage { 301 name = "hello"; 302 tag = "latest"; 303 304 copyToRoot = buildEnv { 305 name = "image-root"; 306 paths = [ hello ]; 307 pathsToLink = [ "/bin" ]; 308 }; 309 310 runAsRoot = '' 311 mkdir -p /data 312 echo "some content" > my-file 313 ''; 314 315 config = { 316 Cmd = [ "/bin/hello" ]; 317 WorkingDir = "/data"; 318 }; 319} 320``` 321::: 322 323:::{.example #ex-dockerTools-buildImage-extraCommands} 324# Building a Docker image with `extraCommands` 325 326The following package builds a Docker image with the `hello` executable from the `hello` package. 327It uses `extraCommands` to create a directory and a file inside the image. 328 329This works the same as [](#ex-dockerTools-buildImage-runAsRoot), but uses `extraCommands` instead of `runAsRoot`. 330Note that with `extraCommands`, we can't directly reference `/` and must create files and directories as if we were already on `/`. 331 332```nix 333{ 334 dockerTools, 335 buildEnv, 336 hello, 337}: 338dockerTools.buildImage { 339 name = "hello"; 340 tag = "latest"; 341 342 copyToRoot = buildEnv { 343 name = "image-root"; 344 paths = [ hello ]; 345 pathsToLink = [ "/bin" ]; 346 }; 347 348 extraCommands = '' 349 mkdir -p data 350 echo "some content" > my-file 351 ''; 352 353 config = { 354 Cmd = [ "/bin/hello" ]; 355 WorkingDir = "/data"; 356 }; 357} 358``` 359::: 360 361:::{.example #ex-dockerTools-buildImage-creatednow} 362# Building a Docker image with a creation date set to the current time 363 364Note that using a value of `"now"` in the `created` attribute will break reproducibility. 365 366```nix 367{ 368 dockerTools, 369 buildEnv, 370 hello, 371}: 372dockerTools.buildImage { 373 name = "hello"; 374 tag = "latest"; 375 376 created = "now"; 377 378 copyToRoot = buildEnv { 379 name = "image-root"; 380 paths = [ hello ]; 381 pathsToLink = [ "/bin" ]; 382 }; 383 384 config.Cmd = [ "/bin/hello" ]; 385} 386``` 387 388After importing the generated repository tarball with Docker, its CLI will display a reasonable date and sort the images as expected: 389 390```shell 391$ docker image ls 392REPOSITORY TAG IMAGE ID CREATED SIZE 393hello latest de2bf4786de6 About a minute ago 25.2MB 394``` 395::: 396 397## buildLayeredImage {#ssec-pkgs-dockerTools-buildLayeredImage} 398 399`buildLayeredImage` uses [`streamLayeredImage`](#ssec-pkgs-dockerTools-streamLayeredImage) underneath to build a compressed Docker-compatible repository tarball. 400Basically, `buildLayeredImage` runs the script created by `streamLayeredImage` to save the compressed image in the Nix store. 401`buildLayeredImage` supports the same options as `streamLayeredImage`, see [`streamLayeredImage`](#ssec-pkgs-dockerTools-streamLayeredImage) for details. 402 403:::{.note} 404Despite the similar name, [`buildImage`](#ssec-pkgs-dockerTools-buildImage) works completely differently from `buildLayeredImage` and `streamLayeredImage`. 405 406Even though some of the arguments may seem related, they cannot be interchanged. 407::: 408 409You can load the result of this function in Docker with `docker image load`. 410See [](#ex-dockerTools-buildLayeredImage-hello) to see how to do that. 411 412### Examples {#ssec-pkgs-dockerTools-buildLayeredImage-examples} 413 414:::{.example #ex-dockerTools-buildLayeredImage-hello} 415# Building a layered Docker image 416 417The following package builds a layered Docker image that runs the `hello` executable from the `hello` package. 418The Docker image will have name `hello` and tag `latest`. 419 420```nix 421{ dockerTools, hello }: 422dockerTools.buildLayeredImage { 423 name = "hello"; 424 tag = "latest"; 425 426 contents = [ hello ]; 427 428 config.Cmd = [ "/bin/hello" ]; 429} 430``` 431 432The result of building this package is a `.tar.gz` file that can be loaded into Docker: 433 434```shell 435$ nix-build 436(some output removed for clarity) 437building '/nix/store/bk8bnrbw10nq7p8pvcmdr0qf57y6scha-hello.tar.gz.drv'... 438No 'fromImage' provided 439Creating layer 1 from paths: ['/nix/store/i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1'] 440Creating layer 2 from paths: ['/nix/store/ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4'] 441Creating layer 3 from paths: ['/nix/store/ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc'] 442Creating layer 4 from paths: ['/nix/store/9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27'] 443Creating layer 5 from paths: ['/nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1'] 444Creating layer 6 with customisation... 445Adding manifests... 446Done. 447/nix/store/hxcz7snvw7f8rzhbh6mv8jq39d992905-hello.tar.gz 448 449$ docker image load -i /nix/store/hxcz7snvw7f8rzhbh6mv8jq39d992905-hello.tar.gz 450(some output removed for clarity) 451Loaded image: hello:latest 452``` 453::: 454 455## streamLayeredImage {#ssec-pkgs-dockerTools-streamLayeredImage} 456 457`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. 458This 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. 459 460You can load the result of this function in Docker with `docker image load`. 461See [](#ex-dockerTools-streamLayeredImage-hello) to see how to do that. 462 463For 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. 464The function will attempt to create one layer per object in the Nix store that needs to be added to the image. 465In 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. 466 467An additional layer will be created with symlinks to the store paths you specified to be included in the image. 468These symlinks are built with [`symlinkJoin`](#trivial-builder-symlinkJoin), so they will be included in the root of the image. 469See [](#ex-dockerTools-streamLayeredImage-exploringlayers) to understand how these symlinks are laid out in the generated image. 470 471`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). 472 473The resulting repository tarball will list a single image as specified by the `name` and `tag` attributes. 474By default, that image will use a static creation date (see documentation for the `created` and `mtime` attributes). 475This allows the function to produce reproducible images. 476 477### Inputs {#ssec-pkgs-dockerTools-streamLayeredImage-inputs} 478 479`streamLayeredImage` expects one argument with the following attributes: 480 481`name` (String) 482 483: The name of the generated image. 484 485`tag` (String or Null; _optional_) 486 487: Tag of the generated image. 488 If `null`, the hash of the nix derivation will be used as the tag. 489 490 _Default value:_ `null`. 491 492`fromImage`(Path or Null; _optional_) 493 494: The repository tarball of an image to be used as the base for the generated image. 495 It must be a valid Docker image, such as one exported by `docker image save`, or another image built with the `dockerTools` utility functions. 496 This can be seen as an equivalent of `FROM fromImage` in a `Dockerfile`. 497 A value of `null` can be seen as an equivalent of `FROM scratch`. 498 499 If specified, the created layers will be appended to the layers defined in the base image. 500 501 _Default value:_ `null`. 502 503`contents` (Path or List of Paths; _optional_) []{#dockerTools-buildLayeredImage-arg-contents} 504 505: Directories whose contents will be added to the generated image. 506 Things that coerce to paths (e.g. a derivation) can also be used. 507 This can be seen as an equivalent of `ADD contents/ /` in a `Dockerfile`. 508 509 All the contents specified by `contents` will be added as a final layer in the generated image. 510 They will be added as links to the actual files (e.g. links to the store paths). 511 The actual files will be added in previous layers. 512 513 _Default value:_ `[]` 514 515`config` (Attribute Set or Null; _optional_) []{#dockerTools-buildLayeredImage-arg-config} 516 517: Used to specify the configuration of the containers that will be started off the generated image. 518 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). 519 520 If any packages are used directly in `config`, they will be automatically included in the generated image. 521 See [](#ex-dockerTools-streamLayeredImage-configclosure) for an example. 522 523 _Default value:_ `null`. 524 525`architecture` (String; _optional_) 526 527: Used to specify the image architecture. 528 This is useful for multi-architecture builds that don't need cross compiling. 529 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. 530 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`. 531 532 _Default value:_ the same value from `pkgs.go.GOARCH`. 533 534`created` (String; _optional_) 535 536: Specifies the time of creation of the generated image. 537 This date will be used for the image metadata. 538 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. 539 540 :::{.caution} 541 Using `"now"` means that the generated image will not be reproducible anymore (because the date will always change whenever it's built). 542 ::: 543 544 _Default value:_ `"1970-01-01T00:00:01Z"`. 545 546`mtime` (String; _optional_) 547 548: Specifies the time used for the modification timestamp of files within the layers of the generated image. 549 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. 550 551 :::{.caution} 552 Using a non-constant date will cause built layers to have a different hash each time, preventing deduplication. 553 Using `"now"` also means that the generated image will not be reproducible anymore (because the date will always change whenever it's built). 554 ::: 555 556 _Default value:_ `"1970-01-01T00:00:01Z"`. 557 558`uid` (Number; _optional_) []{#dockerTools-buildLayeredImage-arg-uid} 559`gid` (Number; _optional_) []{#dockerTools-buildLayeredImage-arg-gid} 560`uname` (String; _optional_) []{#dockerTools-buildLayeredImage-arg-uname} 561`gname` (String; _optional_) []{#dockerTools-buildLayeredImage-arg-gname} 562 563: Credentials for Nix store ownership. 564 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. 565 566 _Default value:_ `0` / `0` / `"root"` / `"root"` 567 568`maxLayers` (Number; _optional_) []{#dockerTools-buildLayeredImage-arg-maxLayers} 569 570: The maximum number of layers that will be used by the generated image. 571 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`. 572 573 :::{.caution} 574 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. 575 For Docker, see [this issue on GitHub](https://github.com/docker/docs/issues/8230). 576 ::: 577 578 _Default value:_ 100. 579 580`extraCommands` (String; _optional_) 581 582: A bash script that will run in the context of the layer created with the contents specified by `contents`. 583 At the moment this script runs, only the contents directly specified by `contents` will be available as links. 584 585 _Default value:_ `""`. 586 587`fakeRootCommands` (String; _optional_) 588 589: A bash script that will run in the context of the layer created with the contents specified by `contents`. 590 During the process to generate that layer, the script in `extraCommands` will be run first, if specified. 591 After that, a {manpage}`fakeroot(1)` environment will be entered. 592 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. 593 594 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). 595 596 For more details, see the manpage for {manpage}`fakeroot(1)`. 597 598 :::{.caution} 599 Due to how fakeroot works, static binaries cannot perform privileged file operations in `fakeRootCommands`, unless `enableFakechroot` is set to `true`. 600 ::: 601 602 _Default value:_ `""`. 603 604`enableFakechroot` (Boolean; _optional_) 605 606: By default, the script specified in `fakeRootCommands` only runs inside a fakeroot environment. 607 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`. 608 Files in the Nix store will be available. 609 This allows scripts that perform installation in `/` to work as expected. 610 This can be seen as an equivalent of `RUN ...` in a `Dockerfile`. 611 612 _Default value:_ `false` 613 614`includeStorePaths` (Boolean; _optional_) 615 616: The files specified in `contents` are put into layers in the generated image. 617 If `includeStorePaths` is `false`, the actual files will not be included in the generated image, and only links to them will be added instead. 618 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. 619 If you don't provide any extra tooling, the generated image won't run properly. 620 621 See [](#ex-dockerTools-streamLayeredImage-exploringlayers) to understand the impact of setting `includeStorePaths` to `false`. 622 623 _Default value:_ `true` 624 625`includeNixDB` (Boolean; _optional_) 626 627: Populate the nix database in the image with the dependencies of `copyToRoot`. 628 The main purpose is to be able to use nix commands in the container. 629 630 :::{.caution} 631 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. 632 633 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`. 634 ::: 635 636 _Default value:_ `false`. 637 638`passthru` (Attribute Set; _optional_) 639 640: Use this to pass any attributes as [`passthru`](#chap-passthru) for the resulting derivation. 641 642 _Default value:_ `{}` 643 644### Passthru outputs {#ssec-pkgs-dockerTools-streamLayeredImage-passthru-outputs} 645 646`streamLayeredImage` also defines its own [`passthru`](#chap-passthru) attributes: 647 648`imageTag` (String) 649 650: The tag of the generated image. 651 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. 652 `imageTag` allows you to retrieve the value of the tag used in this case. 653 654### Examples {#ssec-pkgs-dockerTools-streamLayeredImage-examples} 655 656:::{.example #ex-dockerTools-streamLayeredImage-hello} 657# Streaming a layered Docker image 658 659The following package builds a **script** which, when run, will stream a layered Docker image that runs the `hello` executable from the `hello` package. 660The Docker image will have name `hello` and tag `latest`. 661 662```nix 663{ dockerTools, hello }: 664dockerTools.streamLayeredImage { 665 name = "hello"; 666 tag = "latest"; 667 668 contents = [ hello ]; 669 670 config.Cmd = [ "/bin/hello" ]; 671} 672``` 673 674The result of building this package is a script. 675Running this script and piping it into `docker image load` gives you the same image that was built in [](#ex-dockerTools-buildLayeredImage-hello). 676Note that in this case, the image is never added to the Nix store, but instead streamed directly into Docker. 677 678```shell 679$ nix-build 680(output removed for clarity) 681/nix/store/wsz2xl8ckxnlb769irvq6jv1280dfvxd-stream-hello 682 683$ /nix/store/wsz2xl8ckxnlb769irvq6jv1280dfvxd-stream-hello | docker image load 684No 'fromImage' provided 685Creating layer 1 from paths: ['/nix/store/i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1'] 686Creating layer 2 from paths: ['/nix/store/ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4'] 687Creating layer 3 from paths: ['/nix/store/ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc'] 688Creating layer 4 from paths: ['/nix/store/9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27'] 689Creating layer 5 from paths: ['/nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1'] 690Creating layer 6 with customisation... 691Adding manifests... 692Done. 693(some output removed for clarity) 694Loaded image: hello:latest 695``` 696::: 697 698:::{.example #ex-dockerTools-streamLayeredImage-exploringlayers} 699# Exploring the layers in an image built with `streamLayeredImage` 700 701Assume the following package, which builds a layered Docker image with the `hello` package. 702 703```nix 704{ dockerTools, hello }: 705dockerTools.streamLayeredImage { 706 name = "hello"; 707 contents = [ hello ]; 708} 709``` 710 711The `hello` package depends on 4 other packages: 712 713```shell 714$ nix-store --query -R $(nix-build -A hello) 715/nix/store/i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1 716/nix/store/ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4 717/nix/store/ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc 718/nix/store/9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27 719/nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1 720``` 721 722This means that all these packages will be included in the image generated by `streamLayeredImage`. 723It will put each package in its own layer, for a total of 5 layers with actual files in them. 724A final layer will be created only with symlinks for the `hello` package. 725 726The image generated will have the following directory structure (some directories were collapsed for readability): 727 728``` 729├── bin 730│ └── hello → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/bin/hello 731├── nix 732│ └── store 733│ ├─⊕ 9y8pmvk8gdwwznmkzxa6pwyah52xy3nk-glibc-2.38-27 734│ ├─⊕ i93s7xxblavsacpy82zdbn4kplsyq48l-libunistring-1.1 735│ ├─⊕ ji01n9vinnj22nbrb86nx8a1ssgpilx8-libidn2-2.3.4 736│ ├─⊕ ldrslljw4rg026nw06gyrdwl78k77vyq-xgcc-12.3.0-libgcc 737│ └─⊕ zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1 738└── share 739 ├── info 740 │ └── hello.info → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/info/hello.info 741 ├─⊕ locale 742 └── man 743 └── man1 744 └── hello.1.gz → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/man/man1/hello.1.gz 745``` 746 747Each of the packages in `/nix/store` comes from a layer in the image. 748The final layer adds the `/bin` and `/share` directories, but they only contain links to the actual files in `/nix/store`. 749 750If 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: 751 752```nix 753{ dockerTools, hello }: 754dockerTools.streamLayeredImage { 755 name = "hello"; 756 contents = [ hello ]; 757 includeStorePaths = false; 758} 759``` 760 761After building this package, the image will have the following directory structure: 762 763``` 764├── bin 765│ └── hello → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/bin/hello 766└── share 767 ├── info 768 │ └── hello.info → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/info/hello.info 769 ├─⊕ locale 770 └── man 771 └── man1 772 └── hello.1.gz → /nix/store/zhl06z4lrfrkw5rp0hnjjfrgsclzvxpm-hello-2.12.1/share/man/man1/hello.1.gz 773``` 774 775Note how the links point to paths in `/nix/store`, but they're not included in the image itself. 776This is why you need extra tooling when using `includeStorePaths`: 777a container created from such image won't find any of the files it needs to run otherwise. 778::: 779 780::: {.example #ex-dockerTools-streamLayeredImage-configclosure} 781# Building a layered Docker image with packages directly in `config` 782 783The closure of `config` is automatically included in the generated image. 784The following package shows a more compact way to create the same output generated in [](#ex-dockerTools-streamLayeredImage-hello). 785 786```nix 787{ 788 dockerTools, 789 hello, 790 lib, 791}: 792dockerTools.streamLayeredImage { 793 name = "hello"; 794 tag = "latest"; 795 config.Cmd = [ "${lib.getExe hello}" ]; 796} 797``` 798::: 799 800[]{#ssec-pkgs-dockerTools-fetchFromRegistry} 801## pullImage {#ssec-pkgs-dockerTools-pullImage} 802 803This 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/). 804By default, the `docker.io` registry is used. 805 806The 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). 807 808This function requires two different types of hashes/digests to be specified: 809 810- One of them is used to identify a unique image within the registry (see the documentation for the `imageDigest` attribute). 811- The other is used by Nix to ensure the contents of the output haven't changed (see the documentation for the `sha256` attribute). 812 813Both 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. 814See [](#ex-dockerTools-pullImage-nixprefetchdocker) for a tool that can help gather these values. 815 816### Inputs {#ssec-pkgs-dockerTools-pullImage-inputs} 817 818`pullImage` expects a single argument with the following attributes: 819 820`imageName` (String) 821 822: Specifies the name of the image to be downloaded, as well as the registry endpoint. 823 By default, the `docker.io` registry is used. 824 To specify a different registry, prepend the endpoint to `imageName`, separated by a slash (`/`). 825 See [](#ex-dockerTools-pullImage-differentregistry) for how to do that. 826 827`imageDigest` (String) 828 829: Specifies the digest of the image to be downloaded. 830 831 :::{.tip} 832 **Why can't I specify a tag to pull from, and have to use a digest instead?** 833 834 Tags are often updated to point to different image contents. 835 The most common example is the `latest` tag, which is usually updated whenever a newer image version is available. 836 837 An image tag isn't enough to guarantee the contents of an image won't change, but a digest guarantees this. 838 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. 839 ::: 840 841`sha256` (String) 842 843: The hash of the image after it is downloaded. 844 Internally, this is passed to the [`outputHash`](https://nixos.org/manual/nix/stable/language/advanced-attributes#adv-attr-outputHash) attribute of the resulting derivation. 845 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`. 846 847`finalImageName` (String; _optional_) 848 849: Specifies the name that will be used for the image after it has been downloaded. 850 This only applies after the image is downloaded, and is not used to identify the image to be downloaded in the registry. 851 Use `imageName` for that instead. 852 853 _Default value:_ the same value specified in `imageName`. 854 855`finalImageTag` (String; _optional_) 856 857: Specifies the tag that will be used for the image after it has been downloaded. 858 This only applies after the image is downloaded, and is not used to identify the image to be downloaded in the registry. 859 860 _Default value:_ `"latest"`. 861 862`os` (String; _optional_) 863 864: Specifies the operating system of the image to pull. 865 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. 866 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`. 867 868 _Default value:_ `"linux"`. 869 870`arch` (String; _optional_) 871 872: Specifies the architecture of the image to pull. 873 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. 874 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`. 875 876 _Default value:_ the same value from `pkgs.go.GOARCH`. 877 878`tlsVerify` (Boolean; _optional_) 879 880: Used to enable or disable HTTPS and TLS certificate verification when communicating with the chosen Docker registry. 881 Setting this to `false` will make `pullImage` connect to the registry through HTTP. 882 883 _Default value:_ `true`. 884 885`name` (String; _optional_) 886 887: The name used for the output in the Nix store path. 888 889 _Default value:_ a value derived from `finalImageName` and `finalImageTag`, with some symbols replaced. 890 It is recommended to treat the default as an opaque value. 891 892### Examples {#ssec-pkgs-dockerTools-pullImage-examples} 893 894::: {.example #ex-dockerTools-pullImage-niximage} 895# Pulling the nixos/nix Docker image from the default registry 896 897This example pulls the [`nixos/nix` image](https://hub.docker.com/r/nixos/nix) and saves it in the Nix store. 898 899```nix 900{ dockerTools }: 901dockerTools.pullImage { 902 imageName = "nixos/nix"; 903 imageDigest = "sha256:b8ea88f763f33dfda2317b55eeda3b1a4006692ee29e60ee54ccf6d07348c598"; 904 finalImageName = "nix"; 905 finalImageTag = "2.19.3"; 906 hash = "sha256-zRwlQs1FiKrvHPaf8vWOR/Tlp1C5eLn1d9pE4BZg3oA="; 907} 908``` 909::: 910 911::: {.example #ex-dockerTools-pullImage-differentregistry} 912# Pulling the nixos/nix Docker image from a specific registry 913 914This example pulls the [`coreos/etcd` image](https://quay.io/repository/coreos/etcd) from the `quay.io` registry. 915 916```nix 917{ dockerTools }: 918dockerTools.pullImage { 919 imageName = "quay.io/coreos/etcd"; 920 imageDigest = "sha256:24a23053f29266fb2731ebea27f915bb0fb2ae1ea87d42d890fe4e44f2e27c5d"; 921 finalImageName = "etcd"; 922 finalImageTag = "v3.5.11"; 923 hash = "sha256-Myw+85f2/EVRyMB3axECdmQ5eh9p1q77FWYKy8YpRWU="; 924} 925``` 926::: 927 928::: {.example #ex-dockerTools-pullImage-nixprefetchdocker} 929# Finding the digest and hash values to use for `dockerTools.pullImage` 930 931Since [`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. 932The tool outputs some text for an attribute set which you can pass directly to `pullImage`. 933 934```shell 935$ nix run nixpkgs#nix-prefetch-docker -- --image-name nixos/nix --image-tag 2.19.3 --arch amd64 --os linux 936(some output removed for clarity) 937Writing manifest to image destination 938-> ImageName: nixos/nix 939-> ImageDigest: sha256:498fa2d7f2b5cb3891a4edf20f3a8f8496e70865099ba72540494cd3e2942634 940-> FinalImageName: nixos/nix 941-> FinalImageTag: latest 942-> ImagePath: /nix/store/4mxy9mn6978zkvlc670g5703nijsqc95-docker-image-nixos-nix-latest.tar 943-> ImageHash: 1q6cf2pdrasa34zz0jw7pbs6lvv52rq2aibgxccbwcagwkg2qj1q 944{ 945 imageName = "nixos/nix"; 946 imageDigest = "sha256:498fa2d7f2b5cb3891a4edf20f3a8f8496e70865099ba72540494cd3e2942634"; 947 hash = "sha256-OEgs3uRPMb4Y629FJXAWZW9q9LqHS/A/GUqr3K5wzOA="; 948 finalImageName = "nixos/nix"; 949 finalImageTag = "latest"; 950} 951``` 952 953It 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. 954By default, `nix-prefetch-docker` will set `os` to `linux` and `arch` to `amd64`. 955 956Run `nix-prefetch-docker --help` for a list of all supported arguments: 957```shell 958$ nix run nixpkgs#nix-prefetch-docker -- --help 959(output removed for clarity) 960``` 961::: 962 963## exportImage {#ssec-pkgs-dockerTools-exportImage} 964 965This 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. 966The difference is that `docker container export` is applied to containers, but `dockerTools.exportImage` applies to Docker images. 967The resulting archive will not contain any image metadata (such as command to run with `docker container run`), only the filesystem contents. 968 969You can use this function to import an archive in Docker with `docker image import`. 970See [](#ex-dockerTools-exportImage-importingDocker) to understand how to do that. 971 972:::{.caution} 973`exportImage` works by unpacking the given image inside a VM. 974Because 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). 975::: 976 977### Inputs {#ssec-pkgs-dockerTools-exportImage-inputs} 978 979`exportImage` expects an argument with the following attributes: 980 981`fromImage` (Attribute Set or String) 982 983: The repository tarball of the image whose filesystem will be exported. 984 It must be a valid Docker image, such as one exported by `docker image save`, or another image built with the `dockerTools` utility functions. 985 986 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. 987 If `name` is specified, `fromImage` can be either an Attribute Set corresponding to a derivation or simply a path to a tarball. 988 989 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`. 990 991`fromImageName` (String or Null; _optional_) 992 993: Used to specify the image within the repository tarball in case it contains multiple images. 994 A value of `null` means that `exportImage` will use the first image available in the repository. 995 996 :::{.note} 997 This must be used with `fromImageTag`. Using only `fromImageName` without `fromImageTag` will make `exportImage` use the first image available in the repository. 998 ::: 999 1000 _Default value:_ `null`. 1001 1002`fromImageTag` (String or Null; _optional_) 1003 1004: Used to specify the image within the repository tarball in case it contains multiple images. 1005 A value of `null` means that `exportImage` will use the first image available in the repository. 1006 1007 :::{.note} 1008 This must be used with `fromImageName`. Using only `fromImageTag` without `fromImageName` will make `exportImage` use the first image available in the repository 1009 ::: 1010 1011 _Default value:_ `null`. 1012 1013`diskSize` (Number; _optional_) 1014 1015: Controls the disk size (in megabytes) of the VM used to unpack the image. 1016 1017 _Default value:_ 1024. 1018 1019`name` (String; _optional_) 1020 1021: The name used for the output in the Nix store path. 1022 1023 _Default value:_ the value of `fromImage.name`. 1024 1025### Examples {#ssec-pkgs-dockerTools-exportImage-examples} 1026 1027:::{.example #ex-dockerTools-exportImage-hello} 1028# Exporting a Docker image with `dockerTools.exportImage` 1029 1030This example first builds a layered image with [`dockerTools.buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage), and then exports its filesystem with `dockerTools.exportImage`. 1031 1032```nix 1033{ dockerTools, hello }: 1034dockerTools.exportImage { 1035 name = "hello"; 1036 fromImage = dockerTools.buildLayeredImage { 1037 name = "hello"; 1038 contents = [ hello ]; 1039 }; 1040} 1041``` 1042 1043When building the package above, we can see the layers of the Docker image being unpacked to produce the final output: 1044 1045```shell 1046$ nix-build 1047(some output removed for clarity) 1048Unpacking base image... 1049From-image name or tag wasn't set. Reading the first ID. 1050Unpacking layer 5731199219418f175d1580dbca05677e69144425b2d9ecb60f416cd57ca3ca42/layer.tar 1051tar: Removing leading `/' from member names 1052Unpacking layer e2897bf34bb78c4a65736510204282d9f7ca258ba048c183d665bd0f3d24c5ec/layer.tar 1053tar: Removing leading `/' from member names 1054Unpacking layer 420aa5876dca4128cd5256da7dea0948e30ef5971712f82601718cdb0a6b4cda/layer.tar 1055tar: Removing leading `/' from member names 1056Unpacking layer ea5f4e620e7906c8ecbc506b5e6f46420e68d4b842c3303260d5eb621b5942e5/layer.tar 1057tar: Removing leading `/' from member names 1058Unpacking layer 65807b9abe8ab753fa97da8fb74a21fcd4725cc51e1b679c7973c97acd47ebcf/layer.tar 1059tar: Removing leading `/' from member names 1060Unpacking layer b7da2076b60ebc0ea6824ef641978332b8ac908d47b2d07ff31b9cc362245605/layer.tar 1061Executing post-mount steps... 1062Packing raw image... 1063[ 1.660036] reboot: Power down 1064/nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello 1065``` 1066 1067The following command lists some of the contents of the output to verify that the structure of the archive is as expected: 1068 1069```shell 1070$ tar --exclude '*/share/*' --exclude 'nix/store/*/*' -tvf /nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello 1071drwxr-xr-x root/0 0 1979-12-31 16:00 ./ 1072drwxr-xr-x root/0 0 1979-12-31 16:00 ./bin/ 1073lrwxrwxrwx root/0 0 1979-12-31 16:00 ./bin/hello -> /nix/store/h92a9jd0lhhniv2q417hpwszd4jhys7q-hello-2.12.1/bin/hello 1074dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/ 1075dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/ 1076dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/05zbwhz8a7i2v79r9j21pl6m6cj0xi8k-libunistring-1.1/ 1077dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/ayg5rhjhi9ic73hqw33mjqjxwv59ndym-xgcc-13.2.0-libgcc/ 1078dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/h92a9jd0lhhniv2q417hpwszd4jhys7q-hello-2.12.1/ 1079dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/m59xdgkgnjbk8kk6k6vbxmqnf82mk9s0-libidn2-2.3.4/ 1080dr-xr-xr-x root/0 0 1979-12-31 16:00 ./nix/store/p3jshbwxiwifm1py0yq544fmdyy98j8a-glibc-2.38-27/ 1081drwxr-xr-x root/0 0 1979-12-31 16:00 ./share/ 1082``` 1083::: 1084 1085:::{.example #ex-dockerTools-exportImage-importingDocker} 1086# Importing an archive built with `dockerTools.exportImage` in Docker 1087 1088We will use the same package from [](#ex-dockerTools-exportImage-hello) and import it into Docker. 1089 1090```nix 1091{ dockerTools, hello }: 1092dockerTools.exportImage { 1093 name = "hello"; 1094 fromImage = dockerTools.buildLayeredImage { 1095 name = "hello"; 1096 contents = [ hello ]; 1097 }; 1098} 1099``` 1100 1101Building and importing it into Docker: 1102 1103```shell 1104$ nix-build 1105(output removed for clarity) 1106/nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello 1107$ docker image import /nix/store/x6a5m7c6zdpqz1d8j7cnzpx9glzzvd2h-hello 1108sha256:1d42dba415e9b298ea0decf6497fbce954de9b4fcb2984f91e307c8fedc1f52f 1109$ docker image ls 1110REPOSITORY TAG IMAGE ID CREATED SIZE 1111<none> <none> 1d42dba415e9 4 seconds ago 32.6MB 1112``` 1113::: 1114 1115:::{.example #ex-dockerTools-exportImage-naming} 1116# Exploring output naming with `dockerTools.exportImage` 1117 1118`exportImage` does not require a `name` attribute if `fromImage` is a derivation, which means that the following works: 1119 1120```nix 1121{ dockerTools, hello }: 1122dockerTools.exportImage { 1123 fromImage = dockerTools.buildLayeredImage { 1124 name = "hello"; 1125 contents = [ hello ]; 1126 }; 1127} 1128``` 1129 1130However, 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: 1131 1132```shell 1133$ nix-build 1134(output removed for clarity) 1135/nix/store/by3f40xvc4l6bkis74l0fj4zsy0djgkn-hello.tar.gz 1136$ file /nix/store/by3f40xvc4l6bkis74l0fj4zsy0djgkn-hello.tar.gz 1137/nix/store/by3f40xvc4l6bkis74l0fj4zsy0djgkn-hello.tar.gz: POSIX tar archive (GNU) 1138``` 1139 1140If the archive was actually compressed, the output of file would've mentioned that fact. 1141Because of this, it may be important to set a proper `name` attribute when using `exportImage` with other functions from `dockerTools`. 1142::: 1143 1144:::{.example #ex-dockerTools-exportImage-fromImagePath} 1145# Using `dockerTools.exportImage` with a path as `fromImage` 1146 1147It is possible to use a path as the value of the `fromImage` attribute when calling `dockerTools.exportImage`. 1148However, when doing so, a `name` attribute **MUST** be specified, or you'll encounter an error when evaluating the Nix code. 1149 1150For this example, we'll assume a Docker tarball image named `image.tar.gz` exists in the same directory where our package is defined: 1151 1152```nix 1153{ dockerTools }: 1154dockerTools.exportImage { 1155 name = "filesystem.tar"; 1156 fromImage = ./image.tar.gz; 1157} 1158``` 1159 1160Building this will give us the expected output: 1161 1162```shell 1163$ nix-build 1164(output removed for clarity) 1165/nix/store/w13l8h3nlkg0zv56k7rj0ai0l2zlf7ss-filesystem.tar 1166``` 1167 1168If you don't specify a `name` attribute, you'll encounter an evaluation error and the package won't build. 1169::: 1170 1171## Environment Helpers {#ssec-pkgs-dockerTools-helpers} 1172 1173When 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. 1174Simple examples are the `env` utility in `/usr/bin/env`, or trusted root TLS/SSL certificates. 1175Such 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. 1176The helpers in this section are packages that provide some of these commonly-needed global files. 1177 1178Most 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). 1179[](#ex-dockerTools-helpers-buildImage) and [](#ex-dockerTools-helpers-buildLayeredImage) show how to include these packages on `dockerTools` functions that build an image. 1180For more details on how that works, see the documentation for the function you're using. 1181 1182### usrBinEnv {#sssec-pkgs-dockerTools-helpers-usrBinEnv} 1183 1184This provides the `env` utility at `/usr/bin/env`. 1185This 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. 1186 1187### binSh {#sssec-pkgs-dockerTools-helpers-binSh} 1188 1189This provides a `/bin/sh` link to the `bash` binary from the `bashInteractive` package. 1190Because of this, it supports cases such as running a command interactively in a container (for example by running `docker container run -it <image_name>`). 1191 1192### caCertificates {#sssec-pkgs-dockerTools-helpers-caCertificates} 1193 1194This 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. 1195The locations currently used are: 1196 1197- `/etc/ssl/certs/ca-bundle.crt` 1198- `/etc/ssl/certs/ca-certificates.crt` 1199- `/etc/pki/tls/certs/ca-bundle.crt` 1200 1201[]{#ssec-pkgs-dockerTools-fakeNss} 1202### fakeNss {#sssec-pkgs-dockerTools-helpers-fakeNss} 1203 1204This is a re-export of the `fakeNss` package from Nixpkgs. 1205See [](#sec-fakeNss). 1206 1207### shadowSetup {#ssec-pkgs-dockerTools-shadowSetup} 1208 1209This 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. 1210It is intended to be used with other dockerTools functions in attributes that expect scripts. 1211After 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. 1212See [](#ex-dockerTools-shadowSetup-buildImage) and [](#ex-dockerTools-shadowSetup-buildLayeredImage) to better understand how to use it. 1213 1214`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. 1215 1216:::{.caution} 1217Using both `fakeNss` and `shadowSetup` at the same time will either cause your build to break or produce unexpected results. 1218Use either `fakeNss` or `shadowSetup` depending on your use case, but avoid using both. 1219::: 1220 1221:::{.note} 1222When 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. 1223See [](#ex-dockerTools-shadowSetup-buildLayeredImage). 1224::: 1225 1226### Examples {#ssec-pkgs-dockerTools-helpers-examples} 1227 1228:::{.example #ex-dockerTools-helpers-buildImage} 1229# Using `dockerTools`'s environment helpers with `buildImage` 1230 1231This example adds the [`binSh`](#sssec-pkgs-dockerTools-helpers-binSh) helper to a basic Docker image built with [`dockerTools.buildImage`](#ssec-pkgs-dockerTools-buildImage). 1232This helper makes it possible to enter a shell inside the container. 1233This is the `buildImage` equivalent of [](#ex-dockerTools-helpers-buildLayeredImage). 1234 1235```nix 1236{ dockerTools, hello }: 1237dockerTools.buildImage { 1238 name = "env-helpers"; 1239 tag = "latest"; 1240 1241 copyToRoot = [ 1242 hello 1243 dockerTools.binSh 1244 ]; 1245} 1246``` 1247 1248After building the image and loading it in Docker, we can create a container based on it and enter a shell inside the container. 1249This is made possible by `binSh`. 1250 1251```shell 1252$ nix-build 1253(some output removed for clarity) 1254/nix/store/2p0i3i04cgjlk71hsn7ll4kxaxxiv4qg-docker-image-env-helpers.tar.gz 1255$ docker image load -i /nix/store/2p0i3i04cgjlk71hsn7ll4kxaxxiv4qg-docker-image-env-helpers.tar.gz 1256(output removed for clarity) 1257$ docker container run --rm -it env-helpers:latest /bin/sh 1258sh-5.2# help 1259GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu) 1260(rest of output removed for clarity) 1261``` 1262::: 1263 1264:::{.example #ex-dockerTools-helpers-buildLayeredImage} 1265# Using `dockerTools`'s environment helpers with `buildLayeredImage` 1266 1267This example adds the [`binSh`](#sssec-pkgs-dockerTools-helpers-binSh) helper to a basic Docker image built with [`dockerTools.buildLayeredImage`](#ssec-pkgs-dockerTools-buildLayeredImage). 1268This helper makes it possible to enter a shell inside the container. 1269This is the `buildLayeredImage` equivalent of [](#ex-dockerTools-helpers-buildImage). 1270 1271```nix 1272{ dockerTools, hello }: 1273dockerTools.buildLayeredImage { 1274 name = "env-helpers"; 1275 tag = "latest"; 1276 1277 contents = [ 1278 hello 1279 dockerTools.binSh 1280 ]; 1281 1282 config = { 1283 Cmd = [ "/bin/hello" ]; 1284 }; 1285} 1286``` 1287 1288After building the image and loading it in Docker, we can create a container based on it and enter a shell inside the container. 1289This is made possible by `binSh`. 1290 1291```shell 1292$ nix-build 1293(some output removed for clarity) 1294/nix/store/rpf47f4z5b9qr4db4ach9yr4b85hjhxq-env-helpers.tar.gz 1295$ docker image load -i /nix/store/rpf47f4z5b9qr4db4ach9yr4b85hjhxq-env-helpers.tar.gz 1296(output removed for clarity) 1297$ docker container run --rm -it env-helpers:latest /bin/sh 1298sh-5.2# help 1299GNU bash, version 5.2.21(1)-release (x86_64-pc-linux-gnu) 1300(rest of output removed for clarity) 1301``` 1302::: 1303 1304:::{.example #ex-dockerTools-shadowSetup-buildImage} 1305# Using `dockerTools.shadowSetup` with `dockerTools.buildImage` 1306 1307This is an example that shows how to use `shadowSetup` with `dockerTools.buildImage`. 1308Note that the extra script in `runAsRoot` uses `groupadd` and `useradd`, which are binaries provided by the `shadow` package. 1309These binaries are added to the `PATH` by the `shadowSetup` script, but only for the duration of `runAsRoot`. 1310 1311```nix 1312{ dockerTools, hello }: 1313dockerTools.buildImage { 1314 name = "shadow-basic"; 1315 tag = "latest"; 1316 1317 copyToRoot = [ hello ]; 1318 1319 runAsRoot = '' 1320 ${dockerTools.shadowSetup} 1321 groupadd -r hello 1322 useradd -r -g hello hello 1323 mkdir /data 1324 chown hello:hello /data 1325 ''; 1326 1327 config = { 1328 Cmd = [ "/bin/hello" ]; 1329 WorkingDir = "/data"; 1330 }; 1331} 1332``` 1333::: 1334 1335:::{.example #ex-dockerTools-shadowSetup-buildLayeredImage} 1336# Using `dockerTools.shadowSetup` with `dockerTools.buildLayeredImage` 1337 1338It accomplishes the same thing as [](#ex-dockerTools-shadowSetup-buildImage), but using `buildLayeredImage` instead. 1339 1340Note that the extra script in `fakeRootCommands` uses `groupadd` and `useradd`, which are binaries provided by the `shadow` package. 1341These binaries are added to the `PATH` by the `shadowSetup` script, but only for the duration of `fakeRootCommands`. 1342 1343```nix 1344{ dockerTools, hello }: 1345dockerTools.buildLayeredImage { 1346 name = "shadow-basic"; 1347 tag = "latest"; 1348 1349 contents = [ hello ]; 1350 1351 fakeRootCommands = '' 1352 ${dockerTools.shadowSetup} 1353 groupadd -r hello 1354 useradd -r -g hello hello 1355 mkdir /data 1356 chown hello:hello /data 1357 ''; 1358 enableFakechroot = true; 1359 1360 config = { 1361 Cmd = [ "/bin/hello" ]; 1362 WorkingDir = "/data"; 1363 }; 1364} 1365``` 1366::: 1367 1368[]{#ssec-pkgs-dockerTools-buildNixShellImage-arguments} 1369## buildNixShellImage {#ssec-pkgs-dockerTools-buildNixShellImage} 1370 1371`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. 1372Basically, `buildNixShellImage` runs the script created by `streamNixShellImage` to save the compressed image in the Nix store. 1373 1374`buildNixShellImage` supports the same options as `streamNixShellImage`, see [`streamNixShellImage`](#ssec-pkgs-dockerTools-streamNixShellImage) for details. 1375 1376[]{#ssec-pkgs-dockerTools-buildNixShellImage-example} 1377### Examples {#ssec-pkgs-dockerTools-buildNixShellImage-examples} 1378 1379:::{.example #ex-dockerTools-buildNixShellImage-hello} 1380# Building a Docker image with `buildNixShellImage` with the build environment for the `hello` package 1381 1382This example shows how to build the `hello` package inside a Docker container built with `buildNixShellImage`. 1383The Docker image generated will have a name like `hello-<version>-env` and tag `latest`. 1384This example is the `buildNixShellImage` equivalent of [](#ex-dockerTools-streamNixShellImage-hello). 1385 1386```nix 1387{ dockerTools, hello }: 1388dockerTools.buildNixShellImage { 1389 drv = hello; 1390 tag = "latest"; 1391} 1392``` 1393 1394The result of building this package is a `.tar.gz` file that can be loaded into Docker: 1395 1396```shell 1397$ nix-build 1398(some output removed for clarity) 1399/nix/store/pkj1sgzaz31wl0pbvbg3yp5b3kxndqms-hello-2.12.1-env.tar.gz 1400 1401$ docker image load -i /nix/store/pkj1sgzaz31wl0pbvbg3yp5b3kxndqms-hello-2.12.1-env.tar.gz 1402(some output removed for clarity) 1403Loaded image: hello-2.12.1-env:latest 1404``` 1405 1406After starting an interactive container, the derivation can be built by running `buildDerivation`, and the output can be executed as expected: 1407 1408```shell 1409$ docker container run -it hello-2.12.1-env:latest 1410[nix-shell:~]$ buildDerivation 1411Running phase: unpackPhase 1412unpacking source archive /nix/store/pa10z4ngm0g83kx9mssrqzz30s84vq7k-hello-2.12.1.tar.gz 1413source root is hello-2.12.1 1414(some output removed for clarity) 1415Running phase: fixupPhase 1416shrinking RPATHs of ELF executables and libraries in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1 1417shrinking /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin/hello 1418checking for references to /build/ in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1... 1419gzipping man pages under /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/share/man/ 1420patching script interpreter paths in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1 1421stripping (with command strip and flags -S -p) in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin 1422 1423[nix-shell:~]$ $out/bin/hello 1424Hello, world! 1425``` 1426::: 1427 1428## streamNixShellImage {#ssec-pkgs-dockerTools-streamNixShellImage} 1429 1430`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. 1431This 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. 1432See [](#ex-dockerTools-streamNixShellImage-hello) to understand how to load in Docker the image generated by this script. 1433 1434The 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. 1435It also behaves like an interactive `nix-shell`, running things like `shellHook` (see [](#ex-dockerTools-streamNixShellImage-addingShellHook)) and setting an interactive prompt. 1436If 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`). 1437 1438::: {.caution} 1439The 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. 1440::: 1441 1442### Inputs {#ssec-pkgs-dockerTools-streamNixShellImage-inputs} 1443 1444`streamNixShellImage` expects one argument with the following attributes: 1445 1446`drv` (Attribute Set) 1447 1448: The derivation for which the environment in the image will be set up. 1449 Adding packages to the Docker image is possible by extending the list of `nativeBuildInputs` of this derivation. 1450 See [](#ex-dockerTools-streamNixShellImage-extendingBuildInputs) for how to do that. 1451 Similarly, you can extend the image initialization script by extending `shellHook`. 1452 [](#ex-dockerTools-streamNixShellImage-addingShellHook) shows how to do that. 1453 1454`name` (String; _optional_) 1455 1456: The name of the generated image. 1457 1458 _Default value:_ the value of `drv.name + "-env"`. 1459 1460`tag` (String or Null; _optional_) 1461 1462: Tag of the generated image. 1463 If `null`, the hash of the nix derivation that builds the Docker image will be used as the tag. 1464 1465 _Default value:_ `null`. 1466 1467`uid` (Number; _optional_) 1468 1469: The user ID to run the container as. 1470 This can be seen as a `nixbld` build user. 1471 1472 _Default value:_ 1000. 1473 1474`gid` (Number; _optional_) 1475 1476: The group ID to run the container as. 1477 This can be seen as a `nixbld` build group. 1478 1479 _Default value:_ 1000. 1480 1481`homeDirectory` (String; _optional_) 1482 1483: The home directory of the user the container is running as. 1484 1485 _Default value:_ `/build`. 1486 1487`shell` (String; _optional_) 1488 1489: The path to the `bash` binary to use as the shell. 1490 This shell is started when running the image. 1491 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)`. 1492 1493 _Default value:_ the `bash` binary from the `bashInteractive` package. 1494 1495`command` (String or Null; _optional_) 1496 1497: If specified, this command will be run in the environment of the derivation in an interactive shell. 1498 A call to `exit` will be added after the command if it is specified, so the shell will exit after it's finished running. 1499 This can be seen as an equivalent of the `--command` option in {manpage}`nix-shell(1)`. 1500 1501 _Default value:_ `null`. 1502 1503`run` (String or Null; _optional_) 1504 1505: Similar to the `command` attribute, but runs the command in a non-interactive shell instead. 1506 A call to `exit` will be added after the command if it is specified, so the shell will exit after it's finished running. 1507 This can be seen as an equivalent of the `--run` option in {manpage}`nix-shell(1)`. 1508 1509 _Default value:_ `null`. 1510 1511### Examples {#ssec-pkgs-dockerTools-streamNixShellImage-examples} 1512 1513:::{.example #ex-dockerTools-streamNixShellImage-hello} 1514# Building a Docker image with `streamNixShellImage` with the build environment for the `hello` package 1515 1516This example shows how to build the `hello` package inside a Docker container built with `streamNixShellImage`. 1517The Docker image generated will have a name like `hello-<version>-env` and tag `latest`. 1518This example is the `streamNixShellImage` equivalent of [](#ex-dockerTools-buildNixShellImage-hello). 1519 1520```nix 1521{ dockerTools, hello }: 1522dockerTools.streamNixShellImage { 1523 drv = hello; 1524 tag = "latest"; 1525} 1526``` 1527 1528The result of building this package is a script. 1529Running this script and piping it into `docker image load` gives you the same image that was built in [](#ex-dockerTools-buildNixShellImage-hello). 1530 1531```shell 1532$ nix-build 1533(some output removed for clarity) 1534/nix/store/8vhznpz2frqazxnd8pgdvf38jscdypax-stream-hello-2.12.1-env 1535 1536$ /nix/store/8vhznpz2frqazxnd8pgdvf38jscdypax-stream-hello-2.12.1-env | docker image load 1537(some output removed for clarity) 1538Loaded image: hello-2.12.1-env:latest 1539``` 1540 1541After starting an interactive container, the derivation can be built by running `buildDerivation`, and the output can be executed as expected: 1542 1543```shell 1544$ docker container run -it hello-2.12.1-env:latest 1545[nix-shell:~]$ buildDerivation 1546Running phase: unpackPhase 1547unpacking source archive /nix/store/pa10z4ngm0g83kx9mssrqzz30s84vq7k-hello-2.12.1.tar.gz 1548source root is hello-2.12.1 1549(some output removed for clarity) 1550Running phase: fixupPhase 1551shrinking RPATHs of ELF executables and libraries in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1 1552shrinking /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin/hello 1553checking for references to /build/ in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1... 1554gzipping man pages under /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/share/man/ 1555patching script interpreter paths in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1 1556stripping (with command strip and flags -S -p) in /nix/store/f2vs29jibd7lwxyj35r9h87h6brgdysz-hello-2.12.1/bin 1557 1558[nix-shell:~]$ $out/bin/hello 1559Hello, world! 1560``` 1561::: 1562 1563:::{.example #ex-dockerTools-streamNixShellImage-extendingBuildInputs} 1564# Adding extra packages to a Docker image built with `streamNixShellImage` 1565 1566This example shows how to add extra packages to an image built with `streamNixShellImage`. 1567In this case, we'll add the `cowsay` package. 1568The Docker image generated will have a name like `hello-<version>-env` and tag `latest`. 1569This example uses [](#ex-dockerTools-streamNixShellImage-hello) as a starting point. 1570 1571```nix 1572{ 1573 dockerTools, 1574 cowsay, 1575 hello, 1576}: 1577dockerTools.streamNixShellImage { 1578 tag = "latest"; 1579 drv = hello.overrideAttrs (old: { 1580 nativeBuildInputs = old.nativeBuildInputs or [ ] ++ [ 1581 cowsay 1582 ]; 1583 }); 1584} 1585``` 1586 1587The result of building this package is a script which can be run and piped into `docker image load` to load the generated image. 1588 1589```shell 1590$ nix-build 1591(some output removed for clarity) 1592/nix/store/h5abh0vljgzg381lna922gqknx6yc0v7-stream-hello-2.12.1-env 1593 1594$ /nix/store/h5abh0vljgzg381lna922gqknx6yc0v7-stream-hello-2.12.1-env | docker image load 1595(some output removed for clarity) 1596Loaded image: hello-2.12.1-env:latest 1597``` 1598 1599After starting an interactive container, we can verify the extra package is available by running `cowsay`: 1600 1601```shell 1602$ docker container run -it hello-2.12.1-env:latest 1603[nix-shell:~]$ cowsay "Hello, world!" 1604 _______________ 1605< Hello, world! > 1606 --------------- 1607 \ ^__^ 1608 \ (oo)\_______ 1609 (__)\ )\/\ 1610 ||----w | 1611 || || 1612``` 1613::: 1614 1615:::{.example #ex-dockerTools-streamNixShellImage-addingShellHook} 1616# Adding a `shellHook` to a Docker image built with `streamNixShellImage` 1617 1618This example shows how to add a `shellHook` command to an image built with `streamNixShellImage`. 1619In this case, we'll simply output the string `Hello, world!`. 1620The Docker image generated will have a name like `hello-<version>-env` and tag `latest`. 1621This example uses [](#ex-dockerTools-streamNixShellImage-hello) as a starting point. 1622 1623```nix 1624{ dockerTools, hello }: 1625dockerTools.streamNixShellImage { 1626 tag = "latest"; 1627 drv = hello.overrideAttrs (old: { 1628 shellHook = '' 1629 ${old.shellHook or ""} 1630 echo "Hello, world!" 1631 ''; 1632 }); 1633} 1634``` 1635 1636The result of building this package is a script which can be run and piped into `docker image load` to load the generated image. 1637 1638```shell 1639$ nix-build 1640(some output removed for clarity) 1641/nix/store/iz4dhdvgzazl5vrgyz719iwjzjy6xlx1-stream-hello-2.12.1-env 1642 1643$ /nix/store/iz4dhdvgzazl5vrgyz719iwjzjy6xlx1-stream-hello-2.12.1-env | docker image load 1644(some output removed for clarity) 1645Loaded image: hello-2.12.1-env:latest 1646``` 1647 1648After starting an interactive container, we can see the result of the `shellHook`: 1649 1650```shell 1651$ docker container run -it hello-2.12.1-env:latest 1652Hello, world! 1653 1654[nix-shell:~]$ 1655``` 1656:::