pkgs.dockerTools is a set of functions for creating and manipulating Docker images according to the Docker Image Specification v1.3.1.
Docker itself is not used to perform any of the operations done by these functions.
buildImage
This function builds a Docker-compatible repository tarball containing a single image.
As such, the result is suitable for being loaded in Docker with docker image load (see for how to do this).
This function will create a single layer for all files (and dependencies) that are specified in its argument. Only new dependencies that are not already in the existing layers will be copied. If you prefer to create multiple layers for the files and dependencies you want to add to the image, see or instead.
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).
The resulting repository tarball will list a single image as specified by the name and tag attributes.
By default, that image will use a static creation date (see documentation for the created attribute).
This allows buildImage to produce reproducible images.
Inputs
buildImage expects an argument with the following attributes:
name(String)-
The name of the generated image.
tag(String or Null; optional)-
Tag of the generated image. If
null, the hash of the nix derivation will be used as the tag.Default value:
null. fromImage(Path or Null; optional)-
The repository tarball of an image to be used as the base for the generated image. It must be a valid Docker image, such as one exported by
docker image save, or another image built with thedockerToolsutility functions. This can be seen as an equivalent ofFROM fromImagein aDockerfile. A value ofnullcan be seen as an equivalent ofFROM scratch.If specified, the layer created by
buildImagewill 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 bybuildImage). Otherwise, the resulting image will contain the single layer created bybuildImage.Default value:
null. fromImageName(String or Null; optional)-
Used to specify the image within the repository tarball in case it contains multiple images. A value of
nullmeans thatbuildImagewill use the first image available in the repository.Default value:
null. fromImageTag(String or Null; optional)-
Used to specify the image within the repository tarball in case it contains multiple images. A value of
nullmeans thatbuildImagewill use the first image available in the repository.Default value:
null. copyToRoot(Path, List of Paths, or Null; optional)-
Files to add to the generated image. Anything that coerces to a path (e.g. a derivation) can also be used. This can be seen as an equivalent of
ADD contents/ /in aDockerfile.Default value:
null. keepContentsDirlinks(Boolean; optional)-
When adding files to the generated image (as specified by
copyToRoot), this attribute controls whether to preserve symlinks to directories. Iffalse, the symlinks will be transformed into directories. This behaves the same asrsync -kwhenkeepContentsDirlinksisfalse, and the same asrsync -KwhenkeepContentsDirlinksistrue.Default value:
false. runAsRoot(String or Null; optional)-
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). The script will be run with a working directory of/. This can be seen as an equivalent ofRUN ...in aDockerfile. A value ofnullmeans that this step in the image generation process will be skipped.See for how to work with this attribute.
Default value:
null. extraCommands(String; optional)-
A bash script that will run before the layer created by
buildImageis finalised. The script will be run on some (opaque) working directory which will become/once the layer is created. This is similar torunAsRoot, but the script specified inextraCommandsis not run as root, and does not involve creating a VM. It is simply run as part of building the derivation that outputs the layer created bybuildImage.See for how to work with this attribute, and subtle differences compared to
runAsRoot.Default value:
"". config(Attribute Set or Null; optional)-
Used to specify the configuration of the containers that will be started off the generated image. Must be an attribute set, with each attribute as listed in the Docker Image Specification v1.3.1.
Default value:
null. architecture(String; optional)-
Used to specify the image architecture. This is useful for multi-architecture builds that don’t need cross compiling. If specified, its value should follow the OCI Image Configuration Specification, which should still be compatible with Docker. According to the linked specification, all possible values for
$GOARCHin the Go docs should be valid, but will commonly be one of386,amd64,arm, orarm64.Default value: the same value from
pkgs.go.GOARCH. diskSize(Number; optional)-
Controls the disk size in MiB (1024x1024 bytes) of the VM used to run the script specified in
runAsRoot. This attribute is ignored ifrunAsRootisnull.Default value: 1024.
buildVMMemorySize(Number; optional)-
Controls the amount of memory in MiB (1024x1024 bytes) provisioned for the VM used to run the script specified in
runAsRoot. This attribute is ignored ifrunAsRootisnull.Default value: 512.
created(String; optional)-
Specifies the time of creation of the generated image. This should be either a date and time formatted according to ISO-8601 or
"now", in which casebuildImagewill use the current date.Default value:
"1970-01-01T00:00:01Z". uid(Number; optional)-
The uid of the user that will own the files packed in the new layer built by
buildImage.Default value: 0.
gid(Number; optional)-
The gid of the group that will own the files packed in the new layer built by
buildImage.Default value: 0.
compressor(String; optional)-
Selects the algorithm used to compress the image.
Default value:
"gz".
Possible values:"none","gz","zstd". includeNixDB(Boolean; optional)-
Populate the nix database in the image with the dependencies of
copyToRoot. The main purpose is to be able to use nix commands in the container.Default value:
false. meta(Attribute Set)-
The
metaattribute of the resulting derivation, as instdenv.mkDerivation. Acceptsdescription,maintainersand any othermetaattributes. contentsDEPRECATED-
This attribute is deprecated, and users are encouraged to use
copyToRootinstead.
Passthru outputs
buildImage defines a few passthru attributes:
buildArgs(Attribute Set)-
The argument passed to
buildImageitself. This allows you to inspect all attributes specified in the argument, as described above. layer(Attribute Set)-
The derivation with the layer created by
buildImage. This allows easier inspection of the contents added bybuildImagein the generated image. imageTag(String)-
The tag of the generated image. This is useful if no tag was specified in the attributes of the argument to
buildImage, because an automatic tag will be used instead.imageTagallows you to retrieve the value of the tag used in this case.
Examples
buildLayeredImage
buildLayeredImage uses streamLayeredImage underneath to build a compressed Docker-compatible repository tarball.
Basically, buildLayeredImage runs the script created by streamLayeredImage to save the compressed image in the Nix store.
buildLayeredImage supports the same options as streamLayeredImage, see streamLayeredImage for details.
You can load the result of this function in Docker with docker image load.
See to see how to do that.
Examples
streamLayeredImage
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.
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.
You can load the result of this function in Docker with docker image load.
See to see how to do that.
For this function, you specify a 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. The function will attempt to create one layer per object in the Nix store that needs to be added to the image. In case there are more objects to include than available layers, the function will put the most “popular” objects in their own layers, and group all remaining objects into a single layer.
An additional layer will be created with symlinks to the store paths you specified to be included in the image.
These symlinks are built with symlinkJoin, so they will be included in the root of the image.
See to understand how these symlinks are laid out in the generated image.
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).
The resulting repository tarball will list a single image as specified by the name and tag attributes.
By default, that image will use a static creation date (see documentation for the created and mtime attributes).
This allows the function to produce reproducible images.
Inputs
streamLayeredImage expects one argument with the following attributes:
name(String)-
The name of the generated image.
tag(String or Null; optional)-
Tag of the generated image. If
null, the hash of the nix derivation will be used as the tag.Default value:
null. fromImage(Path or Null; optional)-
The repository tarball of an image to be used as the base for the generated image. It must be a valid Docker image, such as one exported by
docker image save, or another image built with thedockerToolsutility functions. This can be seen as an equivalent ofFROM fromImagein aDockerfile. A value ofnullcan be seen as an equivalent ofFROM scratch.If specified, the created layers will be appended to the layers defined in the base image.
Default value:
null. contents(Path or List of Paths; optional) []{#dockerTools-buildLayeredImage-arg-contents}-
Directories whose contents will be added to the generated image. Things that coerce to paths (e.g. a derivation) can also be used. This can be seen as an equivalent of
ADD contents/ /in aDockerfile.All the contents specified by
contentswill be added as a final layer in the generated image. They will be added as links to the actual files (e.g., links to the store paths). The actual files will be added in previous layers.Default value:
[] config(Attribute Set or Null; optional) []{#dockerTools-buildLayeredImage-arg-config}-
Used to specify the configuration of the containers that will be started off the generated image. Must be an attribute set, with each attribute as listed in the Docker Image Specification v1.3.0.
If any packages are used directly in
config, they will be automatically included in the generated image. See for an example.Default value:
null. architecture(String; optional)-
Used to specify the image architecture. This is useful for multi-architecture builds that don’t need cross compiling. If specified, its value should follow the OCI Image Configuration Specification, which should still be compatible with Docker. According to the linked specification, all possible values for
$GOARCHin the Go docs should be valid, but will commonly be one of386,amd64,arm, orarm64.Default value: the same value from
pkgs.go.GOARCH. created(String; optional)-
Specifies the time of creation of the generated image. This date will be used for the image metadata. This should be either a date and time formatted according to ISO-8601 or
"now", in which case the current date will be used.Default value:
"1970-01-01T00:00:01Z". mtime(String; optional)-
Specifies the time used for the modification timestamp of files within the layers of the generated image. This should be either a date and time formatted according to ISO-8601 or
"now", in which case the current date will be used.Default value:
"1970-01-01T00:00:01Z". uid(Number; optional) []{#dockerTools-buildLayeredImage-arg-uid}gid(Number; optional) []{#dockerTools-buildLayeredImage-arg-gid}uname(String; optional) []{#dockerTools-buildLayeredImage-arg-uname}gname(String; optional) []{#dockerTools-buildLayeredImage-arg-gname}-
Credentials for Nix store ownership. 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.Default value:
0/0/"root"/"root" maxLayers(Number; optional) []{#dockerTools-buildLayeredImage-arg-maxLayers}-
The maximum number of layers that will be used by the generated image. If a
fromImagewas specified, the number of layers used byfromImagewill be subtracted frommaxLayersto ensure that the image generated will have at mostmaxLayers.Default value: 100.
extraCommands(String; optional)-
A bash script that will run in the context of the layer created with the contents specified by
contents. At the moment this script runs, only the contents directly specified bycontentswill be available as links.Default value:
"". fakeRootCommands(String; optional)-
A bash script that will run in the context of the layer created with the contents specified by
contents. During the process to generate that layer, the script inextraCommandswill be run first, if specified. After that, a {manpage}fakeroot(1)environment will be entered. The script specified infakeRootCommandsruns inside the fakeroot environment, and the layer is then generated from the view of the files inside the fakeroot environment.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).For more details, see the manpage for {manpage}
fakeroot(1).Default value:
"". enableFakechroot(Boolean; optional)-
By default, the script specified in
fakeRootCommandsonly runs inside a fakeroot environment. IfenableFakechrootistrue, a more complete chroot environment will be created usingprootbefore running the script infakeRootCommands. Files in the Nix store will be available. This allows scripts that perform installation in/to work as expected. This can be seen as an equivalent ofRUN ...in aDockerfile.Default value:
false includeStorePaths(Boolean; optional)-
The files specified in
contentsare put into layers in the generated image. IfincludeStorePathsisfalse, the actual files will not be included in the generated image, and only links to them will be added instead. It is not recommended to set this tofalseunless 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. If you don’t provide any extra tooling, the generated image won’t run properly.See to understand the impact of setting
includeStorePathstofalse.Default value:
true includeNixDB(Boolean; optional)-
Populate the nix database in the image with the dependencies of
copyToRoot. The main purpose is to be able to use nix commands in the container.Default value:
false. meta(Attribute Set)-
The
metaattribute of the resulting derivation, as instdenv.mkDerivation. Acceptsdescription,maintainersand any othermetaattributes. passthru(Attribute Set; optional)-
Use this to pass any attributes as
passthrufor the resulting derivation.Default value:
{}
Passthru outputs
streamLayeredImage also defines its own passthru attributes:
imageTag(String)-
The tag of the generated image. 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.
imageTagallows you to retrieve the value of the tag used in this case.
Examples
[]{#ssec-pkgs-dockerTools-fetchFromRegistry}
pullImage
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.
By default, the docker.io registry is used.
The image will be downloaded as an uncompressed Docker-compatible repository tarball, which is suitable for use with other dockerTools functions such as buildImage, buildLayeredImage, and streamLayeredImage.
This function requires two different types of hashes/digests to be specified:
- One of them is used to identify a unique image within the registry (see the documentation for the
imageDigestattribute). - The other is used by Nix to ensure the contents of the output haven’t changed (see the documentation for the
sha256attribute).
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. See for a tool that can help gather these values.
Inputs
pullImage expects a single argument with the following attributes:
imageName(String)-
Specifies the name of the image to be downloaded, as well as the registry endpoint. By default, the
docker.ioregistry is used. To specify a different registry, prepend the endpoint toimageName, separated by a slash (/). See for how to do that. imageDigest(String)-
Specifies the digest of the image to be downloaded.
sha256(String)-
The hash of the image after it is downloaded. Internally, this is passed to the
outputHashattribute of the resulting derivation. 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 inimageDigest. finalImageName(String; optional)-
Specifies the name that will be used for the image after it has been downloaded. This only applies after the image is downloaded, and is not used to identify the image to be downloaded in the registry. Use
imageNamefor that instead.Default value: the same value specified in
imageName. finalImageTag(String; optional)-
Specifies the tag that will be used for the image after it has been downloaded. This only applies after the image is downloaded, and is not used to identify the image to be downloaded in the registry.
Default value:
"latest". os(String; optional)-
Specifies the operating system of the image to pull. If specified, its value should follow the OCI Image Configuration Specification, which should still be compatible with Docker. According to the linked specification, all possible values for
$GOOSin the Go docs should be valid, but will commonly be one ofdarwinorlinux.Default value:
"linux". arch(String; optional)-
Specifies the architecture of the image to pull. If specified, its value should follow the OCI Image Configuration Specification, which should still be compatible with Docker. According to the linked specification, all possible values for
$GOARCHin the Go docs should be valid, but will commonly be one of386,amd64,arm, orarm64.Default value: the same value from
pkgs.go.GOARCH. tlsVerify(Boolean; optional)-
Used to enable or disable HTTPS and TLS certificate verification when communicating with the chosen Docker registry. Setting this to
falsewill makepullImageconnect to the registry through HTTP.Default value:
true. name(String; optional)-
The name used for the output in the Nix store path.
Default value: a value derived from
finalImageNameandfinalImageTag, with some symbols replaced. It is recommended to treat the default as an opaque value.
Examples
exportImage
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.
The difference is that docker container export is applied to containers, but dockerTools.exportImage applies to Docker images.
The resulting archive will not contain any image metadata (such as command to run with docker container run), only the filesystem contents.
You can use this function to import an archive in Docker with docker image import.
See to understand how to do that.
Inputs
exportImage expects an argument with the following attributes:
fromImage(Attribute Set or String)-
The repository tarball of the image whose filesystem will be exported. It must be a valid Docker image, such as one exported by
docker image save, or another image built with thedockerToolsutility functions.If
nameis not specified,fromImagemust be an Attribute Set corresponding to a derivation, i.e. it can’t be a path to a tarball. Ifnameis specified,fromImagecan be either an Attribute Set corresponding to a derivation or simply a path to a tarball.See and to understand the connection between
fromImage,name, and the name used for the output ofexportImage. fromImageName(String or Null; optional)-
Used to specify the image within the repository tarball in case it contains multiple images. A value of
nullmeans thatexportImagewill use the first image available in the repository.Default value:
null. fromImageTag(String or Null; optional)-
Used to specify the image within the repository tarball in case it contains multiple images. A value of
nullmeans thatexportImagewill use the first image available in the repository.Default value:
null. diskSize(Number; optional)-
Controls the disk size (in megabytes) of the VM used to unpack the image.
Default value: 1024.
name(String; optional)-
The name used for the output in the Nix store path.
Default value: the value of
fromImage.name.
Examples
Environment Helpers
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.
Simple examples are the env utility in /usr/bin/env, or trusted root TLS/SSL certificates.
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.
The helpers in this section are packages that provide some of these commonly-needed global files.
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).
and show how to include these packages on dockerTools functions that build an image.
For more details on how that works, see the documentation for the function you’re using.
usrBinEnv
This provides the env utility at /usr/bin/env.
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.
binSh
This provides a /bin/sh link to the bash binary from the bash package.
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>).
caCertificates
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.
The locations currently used are:
/etc/ssl/certs/ca-bundle.crt/etc/ssl/certs/ca-certificates.crt/etc/pki/tls/certs/ca-bundle.crt
[]{#ssec-pkgs-dockerTools-fakeNss}
fakeNss
This is a re-export of the fakeNss package from Nixpkgs.
See .
shadowSetup
This is a string containing a script that sets up files needed for shadow to work (using the shadow package from Nixpkgs), and alters PATH to make all its utilities available in the same script.
It is intended to be used with other dockerTools functions in attributes that expect scripts.
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.
See and to better understand how to use it.
shadowSetup achieves a result similar to 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 and a {manpage}login.defs(5) file.
Examples
[]{#ssec-pkgs-dockerTools-buildNixShellImage-arguments}
buildNixShellImage
buildNixShellImage uses 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.
Basically, buildNixShellImage runs the script created by streamNixShellImage to save the compressed image in the Nix store.
buildNixShellImage supports the same options as streamNixShellImage, see streamNixShellImage for details.
[]{#ssec-pkgs-dockerTools-buildNixShellImage-example}
Examples
streamNixShellImage
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.
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.
See to understand how to load in Docker the image generated by this script.
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.
It also behaves like an interactive nix-shell, running things like shellHook (see ) and setting an interactive prompt.
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).
Inputs
streamNixShellImage expects one argument with the following attributes:
drv(Attribute Set)-
The derivation for which the environment in the image will be set up. Adding packages to the Docker image is possible by extending the list of
nativeBuildInputsof this derivation. See for how to do that. Similarly, you can extend the image initialization script by extendingshellHook. shows how to do that. name(String; optional)-
The name of the generated image.
Default value: the value of
drv.name + "-env". tag(String or Null; optional)-
Tag of the generated image. If
null, the hash of the nix derivation that builds the Docker image will be used as the tag.Default value:
null. uid(Number; optional)-
The user ID to run the container as. This can be seen as a
nixbldbuild user.Default value: 1000.
gid(Number; optional)-
The group ID to run the container as. This can be seen as a
nixbldbuild group.Default value: 1000.
homeDirectory(String; optional)-
The home directory of the user the container is running as.
Default value:
/build. shell(String; optional)-
The path to the
bashbinary to use as the shell. This shell is started when running the image. This can be seen as an equivalent of theNIX_BUILD_SHELLenvironment variable for {manpage}nix-shell(1).Default value: the
bashbinary from thebashpackage. command(String or Null; optional)-
If specified, this command will be run in the environment of the derivation in an interactive shell. A call to
exitwill be added after the command if it is specified, so the shell will exit after it’s finished running. This can be seen as an equivalent of the--commandoption in {manpage}nix-shell(1).Default value:
null. run(String or Null; optional)-
Similar to the
commandattribute, but runs the command in a non-interactive shell instead. A call toexitwill be added after the command if it is specified, so the shell will exit after it’s finished running. This can be seen as an equivalent of the--runoption in {manpage}nix-shell(1).Default value:
null.