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-image
nix build .#project-image
This 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 images
docker load < result
# Check to ensure the image is present
docker images
And finally, you can run the image
docker run project-name:df8356kle02k67654
docker run project-name:df8356kle02k67654
You 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:latest
docker run -it --rm -v .:/build/cxx-example nix_test_app-env:latest
Upload 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:latest
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:latest
As 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:latest
docker run the-registry-url.com/project-name:latest