git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #19024 from adnelson/docker_refactor

dockerTools: add docs to docker build functions

commitd5316884e4177f8d77366886eeffc2d66f599358 authorJörg Thalheim <joerg@higgsboson.tk> dateThu 13 Oct 2016, 11:50 (10 years ago) parentd037837940aafc
3 files changed+425−158
pkgs/build-support/docker/default.nix+305−147 pkgs/build-support/docker/examples.nix+108 pkgs/build-support/vm/default.nix+12−11
pkgs/build-support/docker/default.nix+305−147
@@ -1,12 +1,36 @@
1−{ stdenv, lib, callPackage, runCommand, writeReferencesToFile, writeText, vmTools, writeScript
2−, docker, shadow, utillinux, coreutils, jshon, e2fsprogs, go, pigz, findutils }:
1+{
2+ callPackage,
3+ coreutils,
4+ docker,
5+ e2fsprogs,
6+ findutils,
7+ go,
8+ jshon,
9+ lib,
10+ pkgs,
11+ pigz,
12+ runCommand,
13+ rsync,
14+ shadow,
15+ stdenv,
16+ storeDir ? builtins.storeDir,
17+ utillinux,
18+ vmTools,
19+ writeReferencesToFile,
20+ writeScript,
21+ writeText,
22+}:
323
424# WARNING: this API is unstable and may be subject to backwards-incompatible changes in the future.
5−
25+
626rec {
727
28+ examples = import ./examples.nix {
29+ inherit pkgs buildImage pullImage shadowSetup;
30+ };
31+
832 pullImage = callPackage ./pull.nix {};
9−
33+
1034 # We need to sum layer.tar, not a directory, hence tarsum instead of nix-hash.
1135 # And we cannot untar it, because then we cannot preserve permissions ecc.
1236 tarsum = runCommand "tarsum" {
@@ -23,110 +47,138 @@ rec {
2347
2448 cp tarsum $out
2549 '';
26−
50+
2751 # buildEnv creates symlinks to dirs, which is hard to edit inside the overlay VM
28− mergeDrvs = { drvs, onlyDeps ? false }:
52+ mergeDrvs = {
53+ derivations,
54+ onlyDeps ? false
55+ }:
2956 runCommand "merge-drvs" {
30− inherit drvs onlyDeps;
57+ inherit derivations onlyDeps;
3158 } ''
32− if [ -n "$onlyDeps" ]; then
33− echo $drvs > $out
59+ if [[ -n "$onlyDeps" ]]; then
60+ echo $derivations > $out
3461 exit 0
3562 fi
36−
63+
3764 mkdir $out
38− for drv in $drvs; do
39− echo Merging $drv
40− if [ -d "$drv" ]; then
41− cp -drf --preserve=mode -f $drv/* $out/
65+ for derivation in $derivations; do
66+ echo "Merging $derivation..."
67+ if [[ -d "$derivation" ]]; then
68+ # If it's a directory, copy all of its contents into $out.
69+ cp -drf --preserve=mode -f $derivation/* $out/
4270 else
71+ # Otherwise treat the derivation as a tarball and extract it
72+ # into $out.
4373 tar -C $out -xpf $drv || true
4474 fi
4575 done
4676 '';
47−
48− shellScript = text:
49− writeScript "script.sh" ''
50− #!${stdenv.shell}
51− set -e
52− export PATH=${coreutils}/bin:/bin
53−
54− ${text}
55− '';
5677
78+ # Helper for setting up the base files for managing users and
79+ # groups, only if such files don't exist already. It is suitable for
80+ # being used in a runAsRoot script.
5781 shadowSetup = ''
5882 export PATH=${shadow}/bin:$PATH
5983 mkdir -p /etc/pam.d
60− if [ ! -f /etc/passwd ]; then
84+ if [[ ! -f /etc/passwd ]]; then
6185 echo "root:x:0:0::/root:/bin/sh" > /etc/passwd
6286 echo "root:!x:::::::" > /etc/shadow
6387 fi
64− if [ ! -f /etc/group ]; then
88+ if [[ ! -f /etc/group ]]; then
6589 echo "root:x:0:" > /etc/group
6690 echo "root:x::" > /etc/gshadow
6791 fi
68− if [ ! -f /etc/pam.d/other ]; then
92+ if [[ ! -f /etc/pam.d/other ]]; then
6993 cat > /etc/pam.d/other <<EOF
70−account sufficient pam_unix.so
71−auth sufficient pam_rootok.so
72−password requisite pam_unix.so nullok sha512
73−session required pam_unix.so
74−EOF
94+ account sufficient pam_unix.so
95+ auth sufficient pam_rootok.so
96+ password requisite pam_unix.so nullok sha512
97+ session required pam_unix.so
98+ EOF
7599 fi
76− if [ ! -f /etc/login.defs ]; then
100+ if [[ ! -f /etc/login.defs ]]; then
77101 touch /etc/login.defs
78102 fi
79103 '';
80104
81− runWithOverlay = { name , fromImage ? null, fromImageName ? null, fromImageTag ? null
82− , diskSize ? 1024, preMount ? "", postMount ? "", postUmount ? "" }:
105+ # Run commands in a virtual machine.
106+ runWithOverlay = {
107+ name,
108+ fromImage ? null,
109+ fromImageName ? null,
110+ fromImageTag ? null,
111+ diskSize ? 1024,
112+ preMount ? "",
113+ postMount ? "",
114+ postUmount ? ""
115+ }:
83116 vmTools.runInLinuxVM (
84117 runCommand name {
85− preVM = vmTools.createEmptyImage { size = diskSize; fullName = "docker-run-disk"; };
86−
118+ preVM = vmTools.createEmptyImage {
119+ size = diskSize;
120+ fullName = "docker-run-disk";
121+ };
87122 inherit fromImage fromImageName fromImageTag;
88−
89− buildInputs = [ utillinux e2fsprogs jshon ];
123+
124+ buildInputs = [ utillinux e2fsprogs jshon rsync ];
90125 } ''
91126 rm -rf $out
92−
127+
93128 mkdir disk
94129 mkfs /dev/${vmTools.hd}
95130 mount /dev/${vmTools.hd} disk
96131 cd disk
97132
98− if [ -n "$fromImage" ]; then
99− echo Unpacking base image
133+ if [[ -n "$fromImage" ]]; then
134+ echo "Unpacking base image..."
100135 mkdir image
101136 tar -C image -xpf "$fromImage"
102137
103− if [ -z "$fromImageName" ]; then
104− fromImageName=$(jshon -k < image/repositories|head -n1)
138+ # If the image name isn't set, read it from the image repository json.
139+ if [[ -z "$fromImageName" ]]; then
140+ fromImageName=$(jshon -k < image/repositories | head -n 1)
141+ echo "From-image name wasn't set. Read $fromImageName."
105142 fi
106− if [ -z "$fromImageTag" ]; then
107− fromImageTag=$(jshon -e $fromImageName -k < image/repositories|head -n1)
143+
144+ # If the tag isn't set, use the name as an index into the json
145+ # and read the first key found.
146+ if [[ -z "$fromImageTag" ]]; then
147+ fromImageTag=$(jshon -e $fromImageName -k < image/repositories \
148+ | head -n1)
149+ echo "From-image tag wasn't set. Read $fromImageTag."
108150 fi
109− parentID=$(jshon -e $fromImageName -e $fromImageTag -u < image/repositories)
151+
152+ # Use the name and tag to get the parent ID field.
153+ parentID=$(jshon -e $fromImageName -e $fromImageTag -u \
154+ < image/repositories)
110155 fi
111156
157+ # Unpack all of the parent layers into the image.
112158 lowerdir=""
113− while [ -n "$parentID" ]; do
114− echo Unpacking layer $parentID
159+ while [[ -n "$parentID" ]]; do
160+ echo "Unpacking layer $parentID"
115161 mkdir -p image/$parentID/layer
116162 tar -C image/$parentID/layer -xpf image/$parentID/layer.tar
117163 rm image/$parentID/layer.tar
118164
119165 find image/$parentID/layer -name ".wh.*" -exec bash -c 'name="$(basename {}|sed "s/^.wh.//")"; mknod "$(dirname {})/$name" c 0 0; rm {}' \;
120166
167+ # Get the next lower directory and continue the loop.
121168 lowerdir=$lowerdir''${lowerdir:+:}image/$parentID/layer
122− parentID=$(cat image/$parentID/json|(jshon -e parent -u 2>/dev/null || true))
169+ parentID=$(cat image/$parentID/json \
170+ | (jshon -e parent -u 2>/dev/null || true))
123171 done
124172
125173 mkdir work
126174 mkdir layer
127175 mkdir mnt
128176
129− ${preMount}
177+ ${lib.optionalString (preMount != "") ''
178+ # Execute pre-mount steps
179+ echo "Executing pre-mount steps..."
180+ ${preMount}
181+ ''}
130182
131183 if [ -n "$lowerdir" ]; then
132184 mount -t overlay overlay -olowerdir=$lowerdir,workdir=work,upperdir=layer mnt
@@ -134,13 +186,19 @@ EOF
134186 mount --bind layer mnt
135187 fi
136188
137− ${postMount}
138−
189+ ${lib.optionalString (postMount != "") ''
190+ # Execute post-mount steps
191+ echo "Executing post-mount steps..."
192+ ${postMount}
193+ ''}
194+
139195 umount mnt
140196
141− pushd layer
142− find . -type c -exec bash -c 'name="$(basename {})"; touch "$(dirname {})/.wh.$name"; rm "{}"' \;
143− popd
197+ (
198+ cd layer
199+ cmd='name="$(basename {})"; touch "$(dirname {})/.wh.$name"; rm "{}"'
200+ find . -type c -exec bash -c "$cmd" \;
201+ )
144202
145203 ${postUmount}
146204 '');
@@ -150,76 +208,148 @@ EOF
150208 inherit name fromImage fromImageName fromImageTag diskSize;
151209
152210 postMount = ''
153− echo Packing raw image
211+ echo "Packing raw image..."
154212 tar -C mnt --mtime=0 -cf $out .
155213 '';
156214 };
157−
158− mkPureLayer = { baseJson, contents ? null, extraCommands ? "" }:
159− runCommand "docker-layer" {
215+
216+
217+ # Create an executable shell script which has the coreutils in its
218+ # PATH. Since root scripts are executed in a blank environment, even
219+ # things like `ls` or `echo` will be missing.
220+ shellScript = name: text:
221+ writeScript name ''
222+ #!${stdenv.shell}
223+ set -e
224+ export PATH=${coreutils}/bin:/bin
225+ ${text}
226+ '';
227+
228+ # Create a "layer" (set of files).
229+ mkPureLayer = {
230+ # Name of the layer
231+ name,
232+ # JSON containing configuration and metadata for this layer.
233+ baseJson,
234+ # Files to add to the layer.
235+ contents ? null,
236+ # Additional commands to run on the layer before it is tar'd up.
237+ extraCommands ? ""
238+ }:
239+ runCommand "docker-layer-${name}" {
160240 inherit baseJson contents extraCommands;
161241
162− buildInputs = [ jshon ];
163− } ''
242+ buildInputs = [ jshon rsync ];
243+ }
244+ ''
164245 mkdir layer
165− if [ -n "$contents" ]; then
166− echo Adding contents
167− for c in $contents; do
168− cp -drf $c/* layer/
169− chmod -R ug+w layer/
246+ if [[ -n "$contents" ]]; then
247+ echo "Adding contents..."
248+ for item in $contents; do
249+ echo "Adding $item"
250+ rsync -a $item/ layer/
170251 done
252+ else
253+ echo "No contents to add to layer."
254+ fi
255+
256+ if [[ -n $extraCommands ]]; then
257+ (cd layer; eval "$extraCommands")
171258 fi
172259
173− pushd layer
174− ${extraCommands}
175− popd
176−
177− echo Packing layer
260+ # Tar up the layer and throw it into 'layer.tar'.
261+ echo "Packing layer..."
178262 mkdir $out
179263 tar -C layer --mtime=0 -cf $out/layer.tar .
180− ts=$(${tarsum} < $out/layer.tar)
181− cat ${baseJson} | jshon -s "$ts" -i checksum > $out/json
264+
265+ # Compute a checksum of the tarball.
266+ echo "Computing layer checksum..."
267+ tarsum=$(${tarsum} < $out/layer.tar)
268+
269+ # Add a 'checksum' field to the JSON, with the value set to the
270+ # checksum of the tarball.
271+ cat ${baseJson} | jshon -s "$tarsum" -i checksum > $out/json
272+
273+ # Indicate to docker that we're using schema version 1.0.
182274 echo -n "1.0" > $out/VERSION
275+
276+ echo "Finished building layer '${name}'"
183277 '';
184278
185− mkRootLayer = { runAsRoot, baseJson, fromImage ? null, fromImageName ? null, fromImageTag ? null
186− , diskSize ? 1024, contents ? null, extraCommands ? "" }:
187− let runAsRootScript = writeScript "run-as-root.sh" runAsRoot;
279+ # Make a "root" layer; required if we need to execute commands as a
280+ # privileged user on the image. The commands themselves will be
281+ # performed in a virtual machine sandbox.
282+ mkRootLayer = {
283+ # Name of the image.
284+ name,
285+ # Script to run as root. Bash.
286+ runAsRoot,
287+ # Files to add to the layer. If null, an empty layer will be created.
288+ contents ? null,
289+ # JSON containing configuration and metadata for this layer.
290+ baseJson,
291+ # Existing image onto which to append the new layer.
292+ fromImage ? null,
293+ # Name of the image we're appending onto.
294+ fromImageName ? null,
295+ # Tag of the image we're appending onto.
296+ fromImageTag ? null,
297+ # How much disk to allocate for the temporary virtual machine.
298+ diskSize ? 1024,
299+ # Commands (bash) to run on the layer; these do not require sudo.
300+ extraCommands ? ""
301+ }:
302+ # Generate an executable script from the `runAsRoot` text.
303+ let runAsRootScript = shellScript "run-as-root.sh" runAsRoot;
188304 in runWithOverlay {
189− name = "docker-layer";
190−
305+ name = "docker-layer-${name}";
306+
191307 inherit fromImage fromImageName fromImageTag diskSize;
192308
193− preMount = lib.optionalString (contents != null) ''
194− echo Adding contents
195− for c in ${builtins.toString contents}; do
196− cp -drf $c/* layer/
197− chmod -R ug+w layer/
309+ preMount = lib.optionalString (contents != null && contents != []) ''
310+ echo "Adding contents..."
311+ for item in ${toString contents}; do
312+ echo "Adding $item..."
313+ rsync -a $item/ layer/
198314 done
199315 '';
200316
201317 postMount = ''
202− mkdir -p mnt/{dev,proc,sys,nix/store}
318+ mkdir -p mnt/{dev,proc,sys} mnt${storeDir}
319+
320+ # Mount /dev, /sys and the nix store as shared folders.
203321 mount --rbind /dev mnt/dev
204322 mount --rbind /sys mnt/sys
205− mount --rbind /nix/store mnt/nix/store
323+ mount --rbind ${storeDir} mnt${storeDir}
206324
325+ # Execute the run as root script. See 'man unshare' for
326+ # details on what's going on here; basically this command
327+ # means that the runAsRootScript will be executed in a nearly
328+ # completely isolated environment.
207329 unshare -imnpuf --mount-proc chroot mnt ${runAsRootScript}
208− umount -R mnt/dev mnt/sys mnt/nix/store
209− rmdir --ignore-fail-on-non-empty mnt/dev mnt/proc mnt/sys mnt/nix/store mnt/nix
330+
331+ # Unmount directories and remove them.
332+ umount -R mnt/dev mnt/sys mnt${storeDir}
333+ rmdir --ignore-fail-on-non-empty \
334+ mnt/dev mnt/proc mnt/sys mnt${storeDir} \
335+ mnt$(dirname ${storeDir})
210336 '';
211−
337+
212338 postUmount = ''
213− pushd layer
214− ${extraCommands}
215− popd
339+ (cd layer; eval "${extraCommands}")
216340
217− echo Packing layer
341+ echo "Packing layer..."
218342 mkdir $out
219343 tar -C layer --mtime=0 -cf $out/layer.tar .
344+
345+ # Compute the tar checksum and add it to the output json.
346+ echo "Computing checksum..."
220347 ts=$(${tarsum} < $out/layer.tar)
221348 cat ${baseJson} | jshon -s "$ts" -i checksum > $out/json
349+ # Indicate to docker that we're using schema version 1.0.
222350 echo -n "1.0" > $out/VERSION
351+
352+ echo "Finished building layer '${name}'"
223353 '';
224354 };
225355
@@ -229,116 +359,144 @@ EOF
229359 # 4. compute the layer id
230360 # 5. put the layer in the image
231361 # 6. repack the image
232− buildImage = args@{ name, tag ? "latest"
233− , fromImage ? null, fromImageName ? null, fromImageTag ? null
234− , contents ? null, config ? null, runAsRoot ? null
235− , diskSize ? 1024, extraCommands ? "" }:
362+ buildImage = args@{
363+ # Image name.
364+ name,
365+ # Image tag.
366+ tag ? "latest",
367+ # Parent image, to append to.
368+ fromImage ? null,
369+ # Name of the parent image; will be read from the image otherwise.
370+ fromImageName ? null,
371+ # Tag of the parent image; will be read from the image otherwise.
372+ fromImageTag ? null,
373+ # Files to put on the image (a nix store path or list of paths).
374+ contents ? null,
375+ # Docker config; e.g. what command to run on the container.
376+ config ? null,
377+ # Optional bash script to run on the files prior to fixturizing the layer.
378+ extraCommands ? "",
379+ # Optional bash script to run as root on the image when provisioning.
380+ runAsRoot ? null,
381+ # Size of the virtual machine disk to provision when building the image.
382+ diskSize ? 1024,
383+ }:
236384
237385 let
238−
239386 baseName = baseNameOf name;
240387
388+ # Create a JSON blob of the configuration. Set the date to unix zero.
241389 baseJson = writeText "${baseName}-config.json" (builtins.toJSON {
242− created = "1970-01-01T00:00:01Z";
243− architecture = "amd64";
244− os = "linux";
245− config = config;
390+ created = "1970-01-01T00:00:01Z";
391+ architecture = "amd64";
392+ os = "linux";
393+ config = config;
246394 });
247395
248− layer = (if runAsRoot == null
249− then mkPureLayer { inherit baseJson contents extraCommands; }
250− else mkRootLayer { inherit baseJson fromImage fromImageName fromImageTag contents runAsRoot diskSize extraCommands; });
251− result = runCommand "${baseName}.tar.gz" {
396+ layer =
397+ if runAsRoot == null
398+ then mkPureLayer { inherit name baseJson contents extraCommands; }
399+ else mkRootLayer { inherit name baseJson fromImage fromImageName
400+ fromImageTag contents runAsRoot diskSize
401+ extraCommands; };
402+ result = runCommand "docker-image-${baseName}.tar.gz" {
252403 buildInputs = [ jshon pigz coreutils findutils ];
253−
254404 imageName = name;
255405 imageTag = tag;
256406 inherit fromImage baseJson;
257−
258407 layerClosure = writeReferencesToFile layer;
259−
260− passthru = {
261− buildArgs = args;
262− };
408+ passthru.buildArgs = args;
409+ passthru.layer = layer;
263410 } ''
264411 # Print tar contents:
265412 # 1: Interpreted as relative to the root directory
266413 # 2: With no trailing slashes on directories
267− # This is useful for ensuring that the output matches the values generated by the "find" command
414+ # This is useful for ensuring that the output matches the
415+ # values generated by the "find" command
268416 ls_tar() {
269− for f in $(tar -tf $1 | xargs realpath -ms --relative-to=.); do
270− if [ "$f" != "." ]; then
271− echo "/$f"
272− fi
273− done
417+ for f in $(tar -tf $1 | xargs realpath -ms --relative-to=.); do
418+ if [[ "$f" != "." ]]; then
419+ echo "/$f"
420+ fi
421+ done
274422 }
275−
423+
276424 mkdir image
277425 touch baseFiles
278− if [ -n "$fromImage" ]; then
279− echo Unpacking base image
426+ if [[ -n "$fromImage" ]]; then
427+ echo "Unpacking base image..."
280428 tar -C image -xpf "$fromImage"
281−
282− if [ -z "$fromImageName" ]; then
429+
430+ if [[ -z "$fromImageName" ]]; then
283431 fromImageName=$(jshon -k < image/repositories|head -n1)
284432 fi
285− if [ -z "$fromImageTag" ]; then
286− fromImageTag=$(jshon -e $fromImageName -k < image/repositories|head -n1)
433+ if [[ -z "$fromImageTag" ]]; then
434+ fromImageTag=$(jshon -e $fromImageName -k \
435+ < image/repositories|head -n1)
287436 fi
288− parentID=$(jshon -e $fromImageName -e $fromImageTag -u < image/repositories)
289−
437+ parentID=$(jshon -e $fromImageName -e $fromImageTag -u \
438+ < image/repositories)
439+
290440 for l in image/*/layer.tar; do
291− ls_tar $l >> baseFiles
441+ ls_tar image/*/layer.tar >> baseFiles
292442 done
293443 fi
294444
295445 chmod -R ug+rw image
296−
446+
297447 mkdir temp
298448 cp ${layer}/* temp/
299449 chmod ug+w temp/*
300450
451+ echo "$(dirname ${storeDir})" >> layerFiles
452+ echo '${storeDir}' >> layerFiles
301453 for dep in $(cat $layerClosure); do
302− find $dep -path "${layer}" -prune -o -print >> layerFiles
454+ find $dep >> layerFiles
303455 done
304456
305− if [ -s layerFiles ]; then
306− # FIXME: might not be /nix/store
307− echo '/nix' >> layerFiles
308− echo '/nix/store' >> layerFiles
309− fi
310−
311− echo Adding layer
457+ echo "Adding layer..."
458+ # Record the contents of the tarball with ls_tar.
312459 ls_tar temp/layer.tar >> baseFiles
313− comm <(sort -u baseFiles) <(sort -u layerFiles) -1 -3 > newFiles
314− tar -rpf temp/layer.tar --mtime=0 --no-recursion --files-from newFiles 2>/dev/null || true
315460
316− echo Adding meta
317−
318− if [ -n "$parentID" ]; then
461+ # Get the files in the new layer which were *not* present in
462+ # the old layer, and record them as newFiles.
463+ comm <(sort -n baseFiles|uniq) \
464+ <(sort -n layerFiles|uniq|grep -v ${layer}) -1 -3 > newFiles
465+ # Append the new files to the layer.
466+ tar -rpf temp/layer.tar --mtime=0 --no-recursion --files-from newFiles
467+
468+ echo "Adding meta..."
469+
470+ # If we have a parentID, add it to the json metadata.
471+ if [[ -n "$parentID" ]]; then
319472 cat temp/json | jshon -s "$parentID" -i parent > tmpjson
320473 mv tmpjson temp/json
321474 fi
322−
475+
476+ # Take the sha256 sum of the generated json and use it as the layer ID.
477+ # Compute the size and add it to the json under the 'Size' field.
323478 layerID=$(sha256sum temp/json|cut -d ' ' -f 1)
324479 size=$(stat --printf="%s" temp/layer.tar)
325480 cat temp/json | jshon -s "$layerID" -i id -n $size -i Size > tmpjson
326481 mv tmpjson temp/json
327482
483+ # Use the temp folder we've been working on to create a new image.
328484 mv temp image/$layerID
329−
485+
486+ # Store the json under the name image/repositories.
330487 jshon -n object \
331488 -n object -s "$layerID" -i "$imageTag" \
332489 -i "$imageName" > image/repositories
333490
491+ # Make the image read-only.
334492 chmod -R a-w image
335493
336− echo Cooking the image
494+ echo "Cooking the image..."
337495 tar -C image --mtime=0 -c . | pigz -nT > $out
496+
497+ echo "Finished."
338498 '';
339499
340500 in
341−
342− result;
343−
501+ result;
344502}
pkgs/build-support/docker/examples.nixnew file+108
@@ -0,0 +1,108 @@
1+# Examples of using the docker tools to build packages.
2+#
3+# This file defines several docker images. In order to use an image,
4+# build its derivation with `nix-build`, and then load the result with
5+# `docker load`. For example:
6+#
7+# $ nix-build '<nixpkgs>' -A dockerTools.examples.redis
8+# $ docker load < result
9+
10+{ pkgs, buildImage, pullImage, shadowSetup }:
11+
12+rec {
13+ # 1. basic example
14+ bash = buildImage {
15+ name = "bash";
16+ contents = pkgs.bashInteractive;
17+ };
18+
19+ # 2. service example, layered on another image
20+ redis = buildImage {
21+ name = "redis";
22+ tag = "latest";
23+
24+ # for example's sake, we can layer redis on top of bash or debian
25+ fromImage = bash;
26+ # fromImage = debian;
27+
28+ contents = pkgs.redis;
29+ runAsRoot = ''
30+ mkdir -p /data
31+ '';
32+
33+ config = {
34+ Cmd = [ "/bin/redis-server" ];
35+ WorkingDir = "/data";
36+ Volumes = {
37+ "/data" = {};
38+ };
39+ };
40+ };
41+
42+ # 3. another service example
43+ nginx = let
44+ nginxPort = "80";
45+ nginxConf = pkgs.writeText "nginx.conf" ''
46+ user nginx nginx;
47+ daemon off;
48+ error_log /dev/stdout info;
49+ pid /dev/null;
50+ events {}
51+ http {
52+ access_log /dev/stdout;
53+ server {
54+ listen ${nginxPort};
55+ index index.html;
56+ location / {
57+ root ${nginxWebRoot};
58+ }
59+ }
60+ }
61+ '';
62+ nginxWebRoot = pkgs.writeTextDir "index.html" ''
63+ <html><body><h1>Hello from NGINX</h1></body></html>
64+ '';
65+ in
66+ buildImage {
67+ name = "nginx-container";
68+ contents = pkgs.nginx;
69+
70+ runAsRoot = ''
71+ #!${pkgs.stdenv.shell}
72+ ${shadowSetup}
73+ groupadd --system nginx
74+ useradd --system --gid nginx nginx
75+ '';
76+
77+ config = {
78+ Cmd = [ "nginx" "-c" nginxConf ];
79+ ExposedPorts = {
80+ "${nginxPort}/tcp" = {};
81+ };
82+ };
83+ };
84+
85+ # 4. example of pulling an image. could be used as a base for other images
86+ #
87+ # ***** Currently broken, getting 404s. Perhaps the docker API has changed?
88+ #
89+ #
90+ # debian = pullImage {
91+ # imageName = "debian";
92+ # imageTag = "jessie";
93+ # # this hash will need change if the tag is updated at docker hub
94+ # sha256 = "18kd495lc2k35h03bpcbdjnix17nlqbwf6nmq3sb161blf0dk14q";
95+ # };
96+
97+ # 5. example of multiple contents, emacs and vi happily coexisting
98+ editors = buildImage {
99+ name = "editors";
100+ contents = [
101+ pkgs.coreutils
102+ pkgs.bash
103+ pkgs.emacs
104+ pkgs.vim
105+ pkgs.nano
106+ ];
107+ };
108+}
pkgs/build-support/vm/default.nix+12−11
@@ -1,6 +1,7 @@
11{ pkgs
22, kernel ? pkgs.linux
33, img ? "bzImage"
4+, storeDir ? builtins.storeDir
45, rootModules ?
56 [ "virtio_pci" "virtio_blk" "virtio_balloon" "virtio_rng" "ext4" "unix" "9p" "9pnet_virtio" "rtc_cmos" ]
67}:
@@ -128,8 +129,8 @@ rec {
128129 mount -t devpts none /fs/dev/pts
129130
130131 echo "mounting Nix store..."
131− mkdir -p /fs/nix/store
132− mount -t 9p store /fs/nix/store -o trans=virtio,version=9p2000.L,cache=loose
132+ mkdir -p /fs${storeDir}
133+ mount -t 9p store /fs${storeDir} -o trans=virtio,version=9p2000.L,cache=loose
133134
134135 mkdir -p /fs/tmp /fs/run /fs/var
135136 mount -t tmpfs -o "mode=1777" none /fs/tmp
@@ -172,7 +173,7 @@ rec {
172173 # apparent KVM > 1.5.2 bug.
173174 ${pkgs.utillinux}/bin/hwclock -s
174175
175− export NIX_STORE=/nix/store
176+ export NIX_STORE=${storeDir}
176177 export NIX_BUILD_TOP=/tmp
177178 export TMPDIR=/tmp
178179 export PATH=/empty
@@ -220,7 +221,7 @@ rec {
220221 ${lib.optionalString (pkgs.stdenv.system == "x86_64-linux") "-cpu kvm64"} \
221222 -nographic -no-reboot \
222223 -device virtio-rng-pci \
223− -virtfs local,path=/nix/store,security_model=none,mount_tag=store \
224+ -virtfs local,path=${storeDir},security_model=none,mount_tag=store \
224225 -virtfs local,path=$TMPDIR/xchg,security_model=none,mount_tag=xchg \
225226 -drive file=$diskImage,if=virtio,cache=unsafe,werror=report \
226227 -kernel ${kernel}/${img} \
@@ -298,7 +299,7 @@ rec {
298299
299300 /* Run a derivation in a Linux virtual machine (using Qemu/KVM). By
300301 default, there is no disk image; the root filesystem is a tmpfs,
301− and /nix/store is shared with the host (via the 9P protocol).
302+ and the nix store is shared with the host (via the 9P protocol).
302303 Thus, any pure Nix derivation should run unmodified, e.g. the
303304 call
304305
@@ -434,8 +435,8 @@ rec {
434435 chroot=$(type -tP chroot)
435436
436437 # Make the Nix store available in /mnt, because that's where the RPMs live.
437− mkdir -p /mnt/nix/store
438− ${utillinux}/bin/mount -o bind /nix/store /mnt/nix/store
438+ mkdir -p /mnt${storeDir}
439+ ${utillinux}/bin/mount -o bind ${storeDir} /mnt${storeDir}
439440
440441 # Newer distributions like Fedora 18 require /lib etc. to be
441442 # symlinked to /usr.
@@ -474,7 +475,7 @@ rec {
474475
475476 rm /mnt/.debug
476477
477− ${utillinux}/bin/umount /mnt/nix/store /mnt/tmp ${lib.optionalString unifiedSystemDir "/mnt/proc"}
478+ ${utillinux}/bin/umount /mnt${storeDir} /mnt/tmp ${lib.optionalString unifiedSystemDir "/mnt/proc"}
478479 ${utillinux}/bin/umount /mnt
479480 '';
480481
@@ -605,8 +606,8 @@ rec {
605606 done
606607
607608 # Make the Nix store available in /mnt, because that's where the .debs live.
608− mkdir -p /mnt/inst/nix/store
609− ${utillinux}/bin/mount -o bind /nix/store /mnt/inst/nix/store
609+ mkdir -p /mnt/inst${storeDir}
610+ ${utillinux}/bin/mount -o bind ${storeDir} /mnt/inst${storeDir}
610611 ${utillinux}/bin/mount -o bind /proc /mnt/proc
611612 ${utillinux}/bin/mount -o bind /dev /mnt/dev
612613
@@ -654,7 +655,7 @@ rec {
654655
655656 rm /mnt/.debug
656657
657− ${utillinux}/bin/umount /mnt/inst/nix/store
658+ ${utillinux}/bin/umount /mnt/inst${storeDir}
658659 ${utillinux}/bin/umount /mnt/proc
659660 ${utillinux}/bin/umount /mnt/dev
660661 ${utillinux}/bin/umount /mnt