DEV Community

Kondo Uchio
Kondo Uchio

Posted on

14 2

Writing a small bare-metal container

First, run debootstrap command.

$ sudo mkdir /root/devto
$ sudo debootstrap --variant=minbase \
    jessie \
    /root/devto \
    http://ftp.jp.debian.org/debian
Enter fullscreen mode Exit fullscreen mode

Then, prepare a small ruby script:

# $ cat after-unshare.rb 
#!/usr/bin/env ruby
container_name = ARGV[0]
raise unless container_name
Dir.mkdir "/sys/fs/cgroup/cpu/#{container_name}" rescue puts("skip")
File.write "/sys/fs/cgroup/cpu/#{container_name}/cpu.cfs_period_us", "100000"
File.write "/sys/fs/cgroup/cpu/#{container_name}/cpu.cfs_quota_us",   "30000" # 30%
File.write "/sys/fs/cgroup/cpu/#{container_name}/tasks", $$.to_s
Dir.chroot "/root/#{container_name}"
Dir.chdir "/"
system "mount --make-rprivate /"
system "mount -t proc proc /proc"
system "hostname #{container_name}.example.com"

exec "bash -l"
Enter fullscreen mode Exit fullscreen mode

After all, run this ruby script via unshare(1) with options below:

$ chmod a+x after-unshare.rb
$ sudo unshare \
    --fork \
    --pid \
    --mount \
    --uts \
    `pwd`/after-unshare.rb devto
Enter fullscreen mode Exit fullscreen mode

That's it!! You're got into the container!!

root@devto:/# ps auxf
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.3  0.3  20288  3240 ?        S    05:13   0:00 bash -l
root         7  0.0  0.2  17496  2080 ?        R+   05:13   0:00 ps auxf
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
ben profile image
Ben Halpern

Wow, that's simple.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️