SlideShare a Scribd company logo
1 of 23
Download to read offline
presented by Ian Kluft
Silicon Valley Perl
monthly meeting (online)
October 1, 2020
San Jose/Silicon Valley, California
●
Wrapper module I wrote around Open Source buildah tool
– Buildah itself is from Red Hat, available in most Linux distros
– GitHub: containers/buildah repo
– web site: buildah.io
●
Started as my scripting tool to build containers for Podman
– Still at early stage, now supports all buildah subcommands
●
Provides a front-end to and a layer above buildah
– Perl code can run inside a container namespace to set up the image
– Makes multi-stage builds more convenient
Intro to Linux Containers
●
Linux containers are a process-level system virtualization
– Contrast with Virtual Machines which run separate OS kernel
●
Originally Unix systems provided chroot() to change the
filesystem root of a process and its subprocesses
– Limits access to system in case a process is breached
– chroot wasn’t sufficient isolation
– root user in a chroot jail has full device access to break out
Linux Kernel support for Containerization
cgroups
●
kernel tracks groups of processes descended from a common parent
●
cgroups v1 in Linux 2.6.24 (2007)
– resource limitations: memory, fs cache
– prioritization in CPU & I/O scheduling
– accounting: logging or billing
– control: singal/stop processes in a cgroup, OOM killer
●
cgroups v2 in Linux 4.5 (2016)
– namespace isolation
Linux Kernel support for Containerization
namespaces
●
namespaces compartmentalize resources like a separate system
●
processes inherit namespaces from parent
●
mount – since 2.4.19 (2002)
●
IPC – since 3.0 (2011)
●
network – since 3.0 (2011)
●
UTS/node name – since 3.0 (2011)
●
process ID – since 3.8 (2013)
●
user ID – since 3.8 (2013)
●
cgroups – since 4.6 (2016)
●
time – since 5.4 (2020)
●
syslog - proposed
Docker pioneered container images
●
Dockerfile defines how to
build a container image
– layers of filesystem & config
info
– all can run as containers on
the same Linux kernel
– file format standardized
under OCI Open Container
Initiative
Example container image stacks
dependency APK pkgs
base distro: Alpine
scripts & config
app APK packages
dependency DEB pkgs
base distro: Debian
scripts & config
app DEB packages
dependency RPM pkgs
base distro: Fedora
scripts & config
app RPM packages
Linux kernel
Docker model of containers
●
Docker popularized Linux
containers
●
server daemon runs as root
●
clients access server through
API
●
containers launched from
server
Docker
daemon
local
image
storage
containers
CLI
image
registry
API
Docker model of containers
recurring security concerns
●
root daemon is a big target
– source of many security bugs
●
API adds to attack surface
Docker
daemon
local
image
storage
containers
CLI
attacker
image
registry
API
container ship fire photo by Royal Netherlands Navy
Podman model of containers
●
Podman was made by Red Hat
●
CLI or systemd run podman as a subprocess
●
no daemon: root not required
– what everyone wanted from Docker
●
containers are “rootless” if run by non-root
user
●
user namespaces isolate root in container
from root on host
podman
user
image
storage
containers
CLI image
registry
systemd
Rootless containers with Podman
Podman run as root
(UID 0)
Podman run as non-root (UID
1000)
processes in container
run as root (UID 0)
UID 0 inside container
UID 0 outside container
UID 0 inside container
UID 1000 outside container
processes in container
run as non-root (UID 8)
UID 8 inside container
UID 8 outside container
UID 8 inside container
UID 2131624 outside container
namespaced UID depends on host
/etc/subuid range for UID 1000
UID of a container process on the host depends on UIDs of Podman & inside container
What is Buildah?
●
Open Source tool by Red Hat to build OCI-compatible containers
– OCI containers are compatible with Docker and Kubernetes
●
Replaces the builder portion of Docker
– Named by developers for project leader Dan Walsh’s southern-accent
pronunciation of “builder”
●
Works alongside Podman
– podman runs containers as child processes, not in a root daemon
– “podman build” uses buildah to build container images
– buildah runs containers during build with podman
Buildah command line interface
●
buildah CLI uses subcommands similar to git
– buildah command args
●
most buildah subcommands look like lines from a Dockerfile
– each perform a step in building a container image
●
additional subcommands:
– build-using-dockerfile or “bud” - does a build from a Dockerfile
– unshare – “user-namespace share”, run a command in a namespace
●
Container::Buildah re-runs itself to continue inside a container namespace
– other container management: containers, info, inspect, manifest, etc
Buildah CLI subcommands
1 of 2
add Add content to the container
build-using-dockerfile Build an image using instructions in a Dockerfile
commit Create an image from a working container
config Update image configuration settings
containers List working containers and their base images
copy Copy content into the container
from Create a working container based on an image
images List images in local storage
info Display Buildah system information
inspect Inspect the configuration of a container or image
login Login to a container registry
logout Logout of a container registry
Buildah CLI subcommands
2 of 2
manifest Manipulate manifest lists and image indexes
mount Mount a working container's root filesystem
pull Pull an image from the specified location
push Push an image to a specified destination
rename Rename a container
rm Remove one or more working containers
rmi Remove one or more images from local storage
run Run a command inside of the container
tag Add an additional name to a local image
umount Unmount the root file system of the specified working containers
unshare Run a command in a modified user namespace
version Display the Buildah version information
Perl module Container::Buildah
●
wrapper functions for each buildah CLI subcommand
●
seamless entry into build container namespace
– avoids the hurdle of separate scripts outside & inside container
●
support for multi-stage container builds
– one or more container stages to build prerequisites
– only keep the build product, such as a library or app, not the compilers/tools
– final stage builds container image from prerequisites
– configuration specifies “produces” directory or “consumes” stage-name
– Container::Buildah runs stages in order of dependencies
●
it adds a missing layer by jumping through the hoops for you
– regains Dockerfile advantage of easing entry to container namespace
Container::Buildah code overview
●
version 0.3.0 is current – released today
●
3 classes (line counts include POD, comments & blanks)
Container::Buildah 700+ lines
Container::Buildah::Subcommand 1100+ lines
Container::Buildah::Stage 700+ lines
●
200+ unit test cases in 8 scripts
– 1600+ lines under t/ directory
Container::Buildah class
●
top-level front end of the package
●
singleton design pattern – one instance
●
Container::Buildah::init_config(key => value, …)
– sets configuration of container build
●
values may include other config items with Perl’s Template Toolkit macros
– sets callback functions for each build stage
●
Container::Buildah::main()
– process command line and run container build
●
imports wrapper methods from Container::Buildah::Subcommand
Container::Buildah::Subcommand
●
methods for executing external commands
●
wrapper methods for buildah subcommand
– except those that need a container id
●
those are methods of Container::Buildah::Stage
– should be called as methods of Container::Buildah
●
CLI flags in 1st
argument as a hash reference
– boolean flags require a 1 or 0 value for true/false
●
arguments otherwise are same order as CLI
Container::Buildah::Stage
●
contents
– container ID of a stage
– accessors to config tree for the stage
●
Callback functions for each build stage are passed an object of
this type
– methods do not have a container ID parameter – comes from the object
●
implements subcommands which require container ID
– add, commit, config, copy, run
Example: Hello World in C
initialization and configuration
use Container::Buildah;
use YAML::XS;
# set paths as constants
# directory for build stage to make its
binaries
my $build_dir = "/opt/hello-build";
# directory for build stage to save product
files
my $bin_dir = "/opt/hello-bin";
# input directory
my $hello_src = "hello.c";
# YAML config file
my $hello_bin = "hello";
# container parameters
Container::Buildah::init_config(
basename => "hello",
base_image => 'docker://docker.io/alpine:[% alpine_version %]',
required_config => [qw(alpine_version)],
stages => {
build => {
from => "[% base_image %]",
func_exec => &stage_build,
produces => [$bin_dir],
},
runtime => {
from => "[% base_image %]",
consumes => [qw(build)],
func_exec => &stage_runtime,
commit => ["[% basename %]:latest"],
},
},
);
Example: Hello World in C
callbacks for build and runtime stage containers
# container-namespace code for build stage
sub stage_build
{
my $stage = shift;
$stage->debug({level => 1}, "start");
my $input_dir = $cb->get_config('opts', 'inputs');
$stage->run(
# install dependencies
[qw(/sbin/apk add --no-cache binutils gcc musl-dev)],
# create build and product directories
["mkdir", $build_dir, $bin_dir],
);
$stage->config({workingdir => $build_dir});
$stage->copy({dest => $build_dir}, $input_dir."/"
.$hello_src);
$stage->run(
["gcc", "--std=c17", $hello_src, "-o",
"$bin_dir/$hello_bin"],
);
}
# container-namespace code for runtime stage
sub stage_runtime
{
my $stage = shift;
$stage->debug({level => 1}, "start");
my $cb = Container::Buildah->instance();
# container environment
$stage->config({
entrypoint => $bin_dir.'/'.$hello_bin,
});
}
# main
Container::Buildah::main();
Example: Hello World in C
building and running the example
●
build it
$ perl hello_build.pl
●
after it builds, use podman to run it
$ podman run -it hello:latest
Hello world!
Questions?
CPAN: https://metacpan.org/pod/Container::Buildah
Github: https://github.com/ikluft/Container-Buildah

More Related Content

What's hot

OpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgart
OpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgartOpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgart
OpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgart
Tobias Schneck
 

What's hot (20)

Web fundamentals
Web fundamentalsWeb fundamentals
Web fundamentals
 
Ruby microservices with Docker - Sergii Koba
Ruby microservices with Docker -  Sergii KobaRuby microservices with Docker -  Sergii Koba
Ruby microservices with Docker - Sergii Koba
 
docker
dockerdocker
docker
 
Dockerized maven
Dockerized mavenDockerized maven
Dockerized maven
 
Docker
DockerDocker
Docker
 
Testing fácil con Docker: Gestiona dependencias y unifica entornos
Testing fácil con Docker: Gestiona dependencias y unifica entornosTesting fácil con Docker: Gestiona dependencias y unifica entornos
Testing fácil con Docker: Gestiona dependencias y unifica entornos
 
Dockerize the World
Dockerize the WorldDockerize the World
Dockerize the World
 
Pipeline as code - new feature in Jenkins 2
Pipeline as code - new feature in Jenkins 2Pipeline as code - new feature in Jenkins 2
Pipeline as code - new feature in Jenkins 2
 
OCI Runtime Spec
OCI Runtime SpecOCI Runtime Spec
OCI Runtime Spec
 
sed.pdf
sed.pdfsed.pdf
sed.pdf
 
Dockerfiles building docker images automatically v (workdir, env, add, and ...
Dockerfiles   building docker images automatically v (workdir, env, add, and ...Dockerfiles   building docker images automatically v (workdir, env, add, and ...
Dockerfiles building docker images automatically v (workdir, env, add, and ...
 
OpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgart
OpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgartOpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgart
OpenShift-Build-Pipelines: Build -> Test -> Run! @JavaForumStuttgart
 
Innovating Out in the Open
Innovating Out in the Open Innovating Out in the Open
Innovating Out in the Open
 
Accelerate your software development with Docker
Accelerate your software development with DockerAccelerate your software development with Docker
Accelerate your software development with Docker
 
Accelerate your development with Docker
Accelerate your development with DockerAccelerate your development with Docker
Accelerate your development with Docker
 
Docker and the Container Revolution
Docker and the Container RevolutionDocker and the Container Revolution
Docker and the Container Revolution
 
Docker and containers - Presentation Slides by Priyadarshini Anand
Docker and containers - Presentation Slides by Priyadarshini AnandDocker and containers - Presentation Slides by Priyadarshini Anand
Docker and containers - Presentation Slides by Priyadarshini Anand
 
Locally it worked! virtualizing docker
Locally it worked! virtualizing dockerLocally it worked! virtualizing docker
Locally it worked! virtualizing docker
 
OpenShift Build Pipelines @ Lightweight Java User Group Meetup
OpenShift Build Pipelines @ Lightweight Java User Group MeetupOpenShift Build Pipelines @ Lightweight Java User Group Meetup
OpenShift Build Pipelines @ Lightweight Java User Group Meetup
 
Docker for .net developer
Docker for .net developerDocker for .net developer
Docker for .net developer
 

Similar to New Perl module Container::Buildah - SVPerl presentation

Similar to New Perl module Container::Buildah - SVPerl presentation (20)

Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
Develop with docker 2014 aug
Develop with docker 2014 augDevelop with docker 2014 aug
Develop with docker 2014 aug
 
Настройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'aНастройка окружения для кросскомпиляции проектов на основе docker'a
Настройка окружения для кросскомпиляции проектов на основе docker'a
 
Docker based-pipelines
Docker based-pipelinesDocker based-pipelines
Docker based-pipelines
 
Devoxx 2016: A Developer's Guide to OCI and runC
Devoxx 2016: A Developer's Guide to OCI and runCDevoxx 2016: A Developer's Guide to OCI and runC
Devoxx 2016: A Developer's Guide to OCI and runC
 
Using Docker to build and test in your laptop and Jenkins
Using Docker to build and test in your laptop and JenkinsUsing Docker to build and test in your laptop and Jenkins
Using Docker to build and test in your laptop and Jenkins
 
Dockerizing a Symfony2 application
Dockerizing a Symfony2 applicationDockerizing a Symfony2 application
Dockerizing a Symfony2 application
 
Getting Started with Docker
Getting Started with DockerGetting Started with Docker
Getting Started with Docker
 
Docker Basics
Docker BasicsDocker Basics
Docker Basics
 
Docker, but what it is?
Docker, but what it is?Docker, but what it is?
Docker, but what it is?
 
VM vs Docker-Based Pipelines
VM vs Docker-Based PipelinesVM vs Docker-Based Pipelines
VM vs Docker-Based Pipelines
 
Introduction of Docker and Docker Compose
Introduction of Docker and Docker ComposeIntroduction of Docker and Docker Compose
Introduction of Docker and Docker Compose
 
Docker primer and tips
Docker primer and tipsDocker primer and tips
Docker primer and tips
 
Magento Docker Setup.pdf
Magento Docker Setup.pdfMagento Docker Setup.pdf
Magento Docker Setup.pdf
 
Docker
DockerDocker
Docker
 
Tech talk on docker with demo
Tech talk on docker with demoTech talk on docker with demo
Tech talk on docker with demo
 
Docker for developers z java
Docker for developers z javaDocker for developers z java
Docker for developers z java
 
Docker From Scratch
Docker From ScratchDocker From Scratch
Docker From Scratch
 
Cloud Native Computing - Part III - Containers
Cloud Native Computing - Part III - ContainersCloud Native Computing - Part III - Containers
Cloud Native Computing - Part III - Containers
 
Tips pour sécuriser ses conteneurs docker/podman
Tips pour sécuriser ses conteneurs docker/podmanTips pour sécuriser ses conteneurs docker/podman
Tips pour sécuriser ses conteneurs docker/podman
 

More from Ian Kluft

More from Ian Kluft (14)

"#AprilFools Hijinks" at SVPerl April 2021 meeting
"#AprilFools Hijinks" at SVPerl April 2021 meeting"#AprilFools Hijinks" at SVPerl April 2021 meeting
"#AprilFools Hijinks" at SVPerl April 2021 meeting
 
Secure Coding in Perl
Secure Coding in PerlSecure Coding in Perl
Secure Coding in Perl
 
Securing a Raspberry Pi and other DIY IoT devices
Securing a Raspberry Pi and other DIY IoT devicesSecuring a Raspberry Pi and other DIY IoT devices
Securing a Raspberry Pi and other DIY IoT devices
 
Best Practices for Recovering Rocket & Balloon Payloads
Best Practices for Recovering Rocket & Balloon PayloadsBest Practices for Recovering Rocket & Balloon Payloads
Best Practices for Recovering Rocket & Balloon Payloads
 
PiFlash: Linux utility to flash SD cards for Raspberry Pi computers
PiFlash: Linux utility to flash SD cards for Raspberry Pi computersPiFlash: Linux utility to flash SD cards for Raspberry Pi computers
PiFlash: Linux utility to flash SD cards for Raspberry Pi computers
 
Code Generation in Perl
Code Generation in PerlCode Generation in Perl
Code Generation in Perl
 
Aerospace applications of Perl
Aerospace applications of PerlAerospace applications of Perl
Aerospace applications of Perl
 
Command Line Arguments with Getopt::Long
Command Line Arguments with Getopt::LongCommand Line Arguments with Getopt::Long
Command Line Arguments with Getopt::Long
 
Geographic Computation in Perl
Geographic Computation in PerlGeographic Computation in Perl
Geographic Computation in Perl
 
Black Rock Desert Impact Theory
Black Rock Desert Impact TheoryBlack Rock Desert Impact Theory
Black Rock Desert Impact Theory
 
Exception Handling in Perl
Exception Handling in PerlException Handling in Perl
Exception Handling in Perl
 
Geographic Computation in Perl
Geographic Computation in PerlGeographic Computation in Perl
Geographic Computation in Perl
 
Stratofox Aerospace Tracking Team presentation at Space Access 2013
Stratofox Aerospace Tracking Team presentation at Space Access 2013Stratofox Aerospace Tracking Team presentation at Space Access 2013
Stratofox Aerospace Tracking Team presentation at Space Access 2013
 
Pacificon 200905
Pacificon 200905Pacificon 200905
Pacificon 200905
 

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

New Perl module Container::Buildah - SVPerl presentation

  • 1. presented by Ian Kluft Silicon Valley Perl monthly meeting (online) October 1, 2020 San Jose/Silicon Valley, California
  • 2. ● Wrapper module I wrote around Open Source buildah tool – Buildah itself is from Red Hat, available in most Linux distros – GitHub: containers/buildah repo – web site: buildah.io ● Started as my scripting tool to build containers for Podman – Still at early stage, now supports all buildah subcommands ● Provides a front-end to and a layer above buildah – Perl code can run inside a container namespace to set up the image – Makes multi-stage builds more convenient
  • 3. Intro to Linux Containers ● Linux containers are a process-level system virtualization – Contrast with Virtual Machines which run separate OS kernel ● Originally Unix systems provided chroot() to change the filesystem root of a process and its subprocesses – Limits access to system in case a process is breached – chroot wasn’t sufficient isolation – root user in a chroot jail has full device access to break out
  • 4. Linux Kernel support for Containerization cgroups ● kernel tracks groups of processes descended from a common parent ● cgroups v1 in Linux 2.6.24 (2007) – resource limitations: memory, fs cache – prioritization in CPU & I/O scheduling – accounting: logging or billing – control: singal/stop processes in a cgroup, OOM killer ● cgroups v2 in Linux 4.5 (2016) – namespace isolation
  • 5. Linux Kernel support for Containerization namespaces ● namespaces compartmentalize resources like a separate system ● processes inherit namespaces from parent ● mount – since 2.4.19 (2002) ● IPC – since 3.0 (2011) ● network – since 3.0 (2011) ● UTS/node name – since 3.0 (2011) ● process ID – since 3.8 (2013) ● user ID – since 3.8 (2013) ● cgroups – since 4.6 (2016) ● time – since 5.4 (2020) ● syslog - proposed
  • 6. Docker pioneered container images ● Dockerfile defines how to build a container image – layers of filesystem & config info – all can run as containers on the same Linux kernel – file format standardized under OCI Open Container Initiative Example container image stacks dependency APK pkgs base distro: Alpine scripts & config app APK packages dependency DEB pkgs base distro: Debian scripts & config app DEB packages dependency RPM pkgs base distro: Fedora scripts & config app RPM packages Linux kernel
  • 7. Docker model of containers ● Docker popularized Linux containers ● server daemon runs as root ● clients access server through API ● containers launched from server Docker daemon local image storage containers CLI image registry API
  • 8. Docker model of containers recurring security concerns ● root daemon is a big target – source of many security bugs ● API adds to attack surface Docker daemon local image storage containers CLI attacker image registry API container ship fire photo by Royal Netherlands Navy
  • 9. Podman model of containers ● Podman was made by Red Hat ● CLI or systemd run podman as a subprocess ● no daemon: root not required – what everyone wanted from Docker ● containers are “rootless” if run by non-root user ● user namespaces isolate root in container from root on host podman user image storage containers CLI image registry systemd
  • 10. Rootless containers with Podman Podman run as root (UID 0) Podman run as non-root (UID 1000) processes in container run as root (UID 0) UID 0 inside container UID 0 outside container UID 0 inside container UID 1000 outside container processes in container run as non-root (UID 8) UID 8 inside container UID 8 outside container UID 8 inside container UID 2131624 outside container namespaced UID depends on host /etc/subuid range for UID 1000 UID of a container process on the host depends on UIDs of Podman & inside container
  • 11. What is Buildah? ● Open Source tool by Red Hat to build OCI-compatible containers – OCI containers are compatible with Docker and Kubernetes ● Replaces the builder portion of Docker – Named by developers for project leader Dan Walsh’s southern-accent pronunciation of “builder” ● Works alongside Podman – podman runs containers as child processes, not in a root daemon – “podman build” uses buildah to build container images – buildah runs containers during build with podman
  • 12. Buildah command line interface ● buildah CLI uses subcommands similar to git – buildah command args ● most buildah subcommands look like lines from a Dockerfile – each perform a step in building a container image ● additional subcommands: – build-using-dockerfile or “bud” - does a build from a Dockerfile – unshare – “user-namespace share”, run a command in a namespace ● Container::Buildah re-runs itself to continue inside a container namespace – other container management: containers, info, inspect, manifest, etc
  • 13. Buildah CLI subcommands 1 of 2 add Add content to the container build-using-dockerfile Build an image using instructions in a Dockerfile commit Create an image from a working container config Update image configuration settings containers List working containers and their base images copy Copy content into the container from Create a working container based on an image images List images in local storage info Display Buildah system information inspect Inspect the configuration of a container or image login Login to a container registry logout Logout of a container registry
  • 14. Buildah CLI subcommands 2 of 2 manifest Manipulate manifest lists and image indexes mount Mount a working container's root filesystem pull Pull an image from the specified location push Push an image to a specified destination rename Rename a container rm Remove one or more working containers rmi Remove one or more images from local storage run Run a command inside of the container tag Add an additional name to a local image umount Unmount the root file system of the specified working containers unshare Run a command in a modified user namespace version Display the Buildah version information
  • 15. Perl module Container::Buildah ● wrapper functions for each buildah CLI subcommand ● seamless entry into build container namespace – avoids the hurdle of separate scripts outside & inside container ● support for multi-stage container builds – one or more container stages to build prerequisites – only keep the build product, such as a library or app, not the compilers/tools – final stage builds container image from prerequisites – configuration specifies “produces” directory or “consumes” stage-name – Container::Buildah runs stages in order of dependencies ● it adds a missing layer by jumping through the hoops for you – regains Dockerfile advantage of easing entry to container namespace
  • 16. Container::Buildah code overview ● version 0.3.0 is current – released today ● 3 classes (line counts include POD, comments & blanks) Container::Buildah 700+ lines Container::Buildah::Subcommand 1100+ lines Container::Buildah::Stage 700+ lines ● 200+ unit test cases in 8 scripts – 1600+ lines under t/ directory
  • 17. Container::Buildah class ● top-level front end of the package ● singleton design pattern – one instance ● Container::Buildah::init_config(key => value, …) – sets configuration of container build ● values may include other config items with Perl’s Template Toolkit macros – sets callback functions for each build stage ● Container::Buildah::main() – process command line and run container build ● imports wrapper methods from Container::Buildah::Subcommand
  • 18. Container::Buildah::Subcommand ● methods for executing external commands ● wrapper methods for buildah subcommand – except those that need a container id ● those are methods of Container::Buildah::Stage – should be called as methods of Container::Buildah ● CLI flags in 1st argument as a hash reference – boolean flags require a 1 or 0 value for true/false ● arguments otherwise are same order as CLI
  • 19. Container::Buildah::Stage ● contents – container ID of a stage – accessors to config tree for the stage ● Callback functions for each build stage are passed an object of this type – methods do not have a container ID parameter – comes from the object ● implements subcommands which require container ID – add, commit, config, copy, run
  • 20. Example: Hello World in C initialization and configuration use Container::Buildah; use YAML::XS; # set paths as constants # directory for build stage to make its binaries my $build_dir = "/opt/hello-build"; # directory for build stage to save product files my $bin_dir = "/opt/hello-bin"; # input directory my $hello_src = "hello.c"; # YAML config file my $hello_bin = "hello"; # container parameters Container::Buildah::init_config( basename => "hello", base_image => 'docker://docker.io/alpine:[% alpine_version %]', required_config => [qw(alpine_version)], stages => { build => { from => "[% base_image %]", func_exec => &stage_build, produces => [$bin_dir], }, runtime => { from => "[% base_image %]", consumes => [qw(build)], func_exec => &stage_runtime, commit => ["[% basename %]:latest"], }, }, );
  • 21. Example: Hello World in C callbacks for build and runtime stage containers # container-namespace code for build stage sub stage_build { my $stage = shift; $stage->debug({level => 1}, "start"); my $input_dir = $cb->get_config('opts', 'inputs'); $stage->run( # install dependencies [qw(/sbin/apk add --no-cache binutils gcc musl-dev)], # create build and product directories ["mkdir", $build_dir, $bin_dir], ); $stage->config({workingdir => $build_dir}); $stage->copy({dest => $build_dir}, $input_dir."/" .$hello_src); $stage->run( ["gcc", "--std=c17", $hello_src, "-o", "$bin_dir/$hello_bin"], ); } # container-namespace code for runtime stage sub stage_runtime { my $stage = shift; $stage->debug({level => 1}, "start"); my $cb = Container::Buildah->instance(); # container environment $stage->config({ entrypoint => $bin_dir.'/'.$hello_bin, }); } # main Container::Buildah::main();
  • 22. Example: Hello World in C building and running the example ● build it $ perl hello_build.pl ● after it builds, use podman to run it $ podman run -it hello:latest Hello world!