Skip to content

Instantly share code, notes, and snippets.

@halkyon
Last active November 7, 2021 06:20
Show Gist options
  • Save halkyon/8358c35c7529c57fcd15ec4892fc3fda to your computer and use it in GitHub Desktop.
Save halkyon/8358c35c7529c57fcd15ec4892fc3fda to your computer and use it in GitHub Desktop.
Create a simple container from scratch using cgroups and namespaces
#!/bin/bash
set -eu
if [ $EUID -ne 0 ]; then
echo "This script must be run as root"
exit 1
fi
ID="cgroup_$((100 + RANDOM % 1000))"
echo "Generated cgroup name: $ID"
WORKING_DIR=$(mktemp -d)
trap "rm -rf $WORKING_DIR" EXIT
echo "Created temp working directory: $WORKING_DIR"
cd "$WORKING_DIR"
echo "Setting up debootstrap of minimal bionic"
debootstrap --variant=minbase bionic . >/dev/null
echo "Creating cgroup $ID"
cgcreate -g "cpu,cpuacct,memory,blkio,devices,freezer:$ID"
cgset -r cpu.shares=200 "$ID"
cgset -r memory.limit_in_bytes=512M "$ID"
echo "Showing CPU stats:"
cgget -r cpu.stat "$ID"
echo "Showing memory stats:"
cgget -r memory.stat "$ID"
echo "Entering namespace executing as cgroup $ID"
cgexec -g "cpu,cpuacct,memory,blkio,devices,freezer:$ID" \
unshare --mount --uts --net --pid --fork --user --map-root-user --mount-proc \
chroot "$WORKING_DIR" \
/bin/sh -c "/bin/mount -t proc proc /proc && /bin/bash"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment