Using Docker with Nix Flakes
Docker Image
You can easily build a docker image using the dockerTools.buildImage attribute provided by Nixpkgs. More details can be found at Nixpkgs Manual: dockerTools.
Building a Docker image with Nix provides the benefit of reproducibility.
For example an image with the following derivation.
packages = {
project-name = pkgs.stdenv.mkDerivation {
#...
};
docker-image = pkgs.dockerTools.buildImage {
name = "project-name";
created = "now";
copyToRoot = pkgs.buildEnv {
name = "image-root";
paths = [ self.packages.${system}.project-name ];
pathsToLink = [ "/bin" ];
};
config = {
Cmd = [ "/bin/project-name" ];
};
};
};packages = {
project-name = pkgs.stdenv.mkDerivation {
#...
};
docker-image = pkgs.dockerTools.buildImage {
name = "project-name";
created = "now";
copyToRoot = pkgs.buildEnv {
name = "image-root";
paths = [ self.packages.${system}.project-name ];
pathsToLink = [ "/bin" ];
};
config = {
Cmd = [ "/bin/project-name" ];
};
};
};Then, in a terminal, run
nix build .#project-imagenix build .#project-imageThis creates a symbolic link to a Tarball named result that can be loaded into Docker. Load this image using docker load
docker load < result
# Check to ensure the image is present
docker imagesdocker load < result
# Check to ensure the image is present
docker imagesAnd finally, you can run the image
docker run project-name:df8356kle02k67654docker run project-name:df8356kle02k67654You may optionally use buildLayeredImage instead of buildImage when creating the Docker image.
Docker Shell Image
Use dockerTools.buildNixShellImage to create Dockerized developer environments.
docker run -it --rm -v .:/build/cxx-example nix_test_app-env:latestdocker run -it --rm -v .:/build/cxx-example nix_test_app-env:latestUpload Image to DockerHub
The below commands are approximate and may not be correct
docker login --username <username> the-registry-url.com
docker tag project-name:latest the-registry-url.com/project-name:latest
docker push the-registry-url.com/project-name:latestdocker login --username <username> the-registry-url.com
docker tag project-name:latest the-registry-url.com/project-name:latest
docker push the-registry-url.com/project-name:latestAs with typical Docker usage, you can run an image from the remote registry using a command like
docker run the-registry-url.com/project-name:latestdocker run the-registry-url.com/project-name:latest