$_ CLI In Depth
Learning progress 0%
Build · Syscalls, Namespaces & cgroups

Build: A Mini Container with unshare and chroot

Create a root filesystem skeleton, write a launcher script with unshare and chroot, and check its syntax.

~40 min Advanced 3 checked steps

Build it on a real Linux machine

The guided lab boots Linux in your browser. Each step runs a check script on that machine, so it passes only when your files and output are right.

What you will build

Step 1: Create the root filesystem skeleton

A container root needs a few directories. Create them under rootfs and give the box a hostname file:

BASH2 lines
mkdir -p rootfs/bin rootfs/proc rootfs/etc
echo mini > rootfs/etc/hostname

Run ls -R rootfs to confirm the directories exist.

Step 2: Write the launcher script

Write run-box.sh. It asks for new namespaces with unshare and then runs a shell inside rootfs with chroot. Running it is optional here, because an unprivileged user usually gets a permission error:

BASH5 lines
cat > run-box.sh <<'EOF'
#!/bin/bash
set -eu
unshare --uts --mount --fork chroot /workspace/rootfs /bin/sh
EOF

The file must mention both unshare and chroot. Keep the script readable, one command per line.

Step 3: Check the script without running it

bash -n reads a script and reports syntax errors without running any command. Run it and save a note when it passes:

BASH1 lines
bash -n run-box.sh && echo "syntax ok" > syntax.txt

Open syntax.txt. It should say syntax ok.

Files

  • walkthrough.sh: every step of the reference solution, in order.

How it is checked

Each step in the guided lab has a check script that runs on the lab machine after you finish. It passes only when the files and output it expects are there, so the lab cannot be completed by reading alone.

Reference files

Read these after you have tried the lab. They are the solutions the checks were verified against.

walkthrough.sh

BASH18 lines
#!/usr/bin/env bash
# Reference solution for every step of the guided lab, in order.

# Step 1: Create the root filesystem skeleton
cd /workspace
mkdir -p rootfs/bin rootfs/proc rootfs/etc
echo mini > rootfs/etc/hostname

# Step 2: Write the launcher script
cat > /workspace/run-box.sh <<&#039;EOF&#039;
#!/bin/bash
set -eu
unshare --uts --mount --fork chroot /workspace/rootfs /bin/sh
EOF

# Step 3: Check the script without running it
cd /workspace
bash -n run-box.sh && echo "syntax ok" > syntax.txt

Lessons this build uses