Skip to content

Instantly share code, notes, and snippets.

@tuxfight3r
Last active October 27, 2020 08:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxfight3r/73308e418714a4d0e41ee156f589f9d6 to your computer and use it in GitHub Desktop.
Save tuxfight3r/73308e418714a4d0e41ee156f589f9d6 to your computer and use it in GitHub Desktop.
container basics cgroups namespaces
# Prepare a hash. We need it to identify our container.
$ uuid="ps_$(shuf -i 42002-42254 -n 1)"
# Prepare a root dir for all the containers.
$ btrfs_path='/var/bocker' && cgroups='cpu,cpuacct,memory';
# Prepare root filesystem based on the given `$image`.
$ btrfs subvolume snapshot "$btrfs_path/$image" "$btrfs_path/$uuid" > /dev/null
# Create a cgroup
$ cgcreate -g "$cgroups:/$uuid"
# Control cgroup resource
$ cgset -r cpu.shares=512 "$uuid"
$ cgset -r memory.limit_in_bytes=512000000 "$uuid"
# Execute a given `$cmd` in the cgroup.
# We need to create a unique namespace for the command (unshare).
# We also need to change the root directory (chroot).
# We also need to mount the runtime (/proc).
# Logging is a bonus (tee).
$ cgexec -g "$cgroups:$uuid" \
ip netns exec netns_"$uuid" \
unshare -fmuip --mount-proc \
chroot "$btrfs_path/$uuid" \
/bin/sh -c "/bin/mount -t proc proc /proc && $cmd" \
2>&1 | tee "$btrfs_path/$uuid/$uuid.log"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment