Created
February 23, 2020 16:34
-
-
Save unclechu/1a9e5461982520f864a5ac221971c345 to your computer and use it in GitHub Desktop.
Nix Docker workshop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
nixpkgs ? import <nixpkgs> {}, | |
name, | |
tag, | |
}: | |
let | |
inherit (nixpkgs) pkgs; | |
inherit (pkgs) dockerTools; | |
in | |
dockerTools.buildLayeredImage { | |
inherit name tag; | |
contents = [ pkgs.hello ]; | |
config.Cmd = [ "${pkgs.hello}/bin/hello" ]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
nixpkgs ? import <nixpkgs> {}, | |
docker-bin ? null, | |
name ? "my-hello", | |
tag ? "my-hello-tag", | |
}: | |
let | |
inherit (nixpkgs) pkgs; | |
inherit (pkgs) writeShellScriptBin; | |
esc = pkgs.lib.escapeShellArg; | |
shExe = pkg: binFile: esc "${pkgs."${pkg}"}/bin/${binFile}"; | |
shExe1 = pkg: shExe pkg pkg; | |
docker = | |
if docker-bin != null | |
then docker-bin | |
else "${pkgs.docker}/bin/docker"; | |
sh.cat = shExe "coreutils" "cat"; | |
sh.nix-build = shExe "nix" "nix-build"; | |
sh.docker = | |
if docker-bin != null | |
then esc docker-bin | |
else shExe1 "docker"; | |
writeShellScriptBinWithDeps = name: deps: text: | |
pkgs.writeTextFile { | |
inherit name; | |
executable = true; | |
destination = "/bin/${name}"; | |
text = "#!${pkgs.runtimeShell}\n${text}"; | |
checkPhase = '' | |
set -Eeuo pipefail | |
${ | |
builtins.foldl' | |
(acc: name: '' | |
${acc} | |
if ! [ -f ${deps."${name}"} -a -x ${deps."${name}"} ]; then | |
exec >&2 | |
printf 'Dependency "%s" could not be satisfied ' ${esc name} | |
printf 'due to file "%s" does not exist ' ${deps."${name}"} | |
echo 'or not an executable!' | |
exit 1 | |
fi | |
'') | |
"" | |
(builtins.attrNames deps) | |
} | |
''; | |
}; | |
containered-hello = writeShellScriptBinWithDeps "containered-hello" sh '' | |
set -Eeuo pipefail | |
DOCKER_IMAGE=$( | |
${sh.nix-build} --argstr name ${esc name} --argstr tag ${esc tag} | |
) | |
>&2 printf 'Docker image path: "%s"\n' "$DOCKER_IMAGE" | |
${sh.cat} -- "$DOCKER_IMAGE" | ${sh.docker} load >&2 | |
# >&2 echo 'Docker images:' | |
# >&2 ${sh.docker} images | |
>&2 echo 'Running "hello" inside a container…' | |
${sh.docker} run -- ${esc name}:${esc tag} | |
''; | |
in | |
pkgs.mkShell { | |
buildInputs = [ containered-hello ]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment