package libcontainer
import "github.com/opencontainers/runc/libcontainer"
Package libcontainer provides a native Go implementation for creating containers
with namespaces, cgroups, capabilities, and filesystem access controls.
It allows you to manage the lifecycle of the container performing additional operations
after the container is created.
Code:play
Example (Container)¶
package main
import (
"log"
"os"
"golang.org/x/sys/unix"
"github.com/opencontainers/cgroups"
"github.com/opencontainers/cgroups/devices/config"
// To enable device management code, import cgroups/devices package.
// Without it, cgroup manager won't be able to set up device access rules,
// and will fail if devices are specified in the container configuration.
_ "github.com/opencontainers/cgroups/devices"
"github.com/opencontainers/runc/libcontainer"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runc/libcontainer/specconv"
// Required for container enter functionality.
_ "github.com/opencontainers/runc/libcontainer/nsenter"
)
func main() {
const defaultMountFlags = unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV
// Default set of allowed devices.
var devices []*config.Rule
for _, device := range specconv.AllowedDevices {
devices = append(devices, &device.Rule)
}
// To create a container you first have to create a configuration
// struct describing how the container is to be created.
config := &configs.Config{
Rootfs: "/your/path/to/rootfs",
Capabilities: &configs.Capabilities{
Bounding: []string{
"CAP_KILL",
"CAP_AUDIT_WRITE",
},
Effective: []string{
"CAP_KILL",
"CAP_AUDIT_WRITE",
},
Permitted: []string{
"CAP_KILL",
"CAP_AUDIT_WRITE",
},
},
Namespaces: configs.Namespaces([]configs.Namespace{
{Type: configs.NEWNS},
{Type: configs.NEWUTS},
{Type: configs.NEWIPC},
{Type: configs.NEWPID},
{Type: configs.NEWUSER},
{Type: configs.NEWNET},
{Type: configs.NEWCGROUP},
}),
Cgroups: &cgroups.Cgroup{
Name: "test-container",
Parent: "system",
Resources: &cgroups.Resources{
MemorySwappiness: nil,
Devices: devices,
},
},
MaskPaths: []string{
"/proc/kcore",
"/sys/firmware",
},
ReadonlyPaths: []string{
"/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus",
},
Devices: specconv.AllowedDevices,
Hostname: "testing",
Mounts: []*configs.Mount{
{
Source: "proc",
Destination: "/proc",
Device: "proc",
Flags: defaultMountFlags,
},
{
Source: "tmpfs",
Destination: "/dev",
Device: "tmpfs",
Flags: unix.MS_NOSUID | unix.MS_STRICTATIME,
Data: "mode=755",
},
{
Source: "devpts",
Destination: "/dev/pts",
Device: "devpts",
Flags: unix.MS_NOSUID | unix.MS_NOEXEC,
Data: "newinstance,ptmxmode=0666,mode=0620,gid=5",
},
{
Device: "tmpfs",
Source: "shm",
Destination: "/dev/shm",
Data: "mode=1777,size=65536k",
Flags: defaultMountFlags,
},
{
Source: "mqueue",
Destination: "/dev/mqueue",
Device: "mqueue",
Flags: defaultMountFlags,
},
{
Source: "sysfs",
Destination: "/sys",
Device: "sysfs",
Flags: defaultMountFlags | unix.MS_RDONLY,
},
},
UIDMappings: []configs.IDMap{
{
ContainerID: 0,
HostID: 1000,
Size: 65536,
},
},
GIDMappings: []configs.IDMap{
{
ContainerID: 0,
HostID: 1000,
Size: 65536,
},
},
Networks: []*configs.Network{
{
Type: "loopback",
Address: "127.0.0.1/0",
Gateway: "localhost",
},
},
Rlimits: []configs.Rlimit{
{
Type: unix.RLIMIT_NOFILE,
Hard: uint64(1025),
Soft: uint64(1025),
},
},
}
// Once you have the configuration populated you can create a container
// with a specified ID under a specified state directory:
container, err := libcontainer.Create("/run/containers", "container-id", config)
if err != nil {
log.Fatal(err)
return
}
// To spawn bash as the initial process inside the container and have the
// processes pid returned in order to wait, signal, or kill the process:
process := &libcontainer.Process{
Args: []string{"/bin/bash"},
Env: []string{"PATH=/bin"},
UID: 0,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Init: true,
}
err = container.Run(process)
if err != nil {
_ = container.Destroy()
log.Fatal(err)
return
}
// Wait for the process to finish.
_, err = process.Wait()
if err != nil {
log.Fatal(err)
}
// Destroy the container.
err = container.Destroy()
if err != nil {
log.Fatal(err)
}
// Additional ways to interact with a running container are:
// Return all the pids for all processes running inside the container.
processes, err := container.Processes()
if err != nil {
log.Fatal(err)
}
log.Print(processes)
// Get detailed cpu, memory, io, and network statistics for the container and
// it's processes.
stats, err := container.Stats()
if err != nil {
log.Fatal(err)
}
log.Print(stats)
// Pause all processes inside the container.
err = container.Pause()
if err != nil {
log.Fatal(err)
}
// Resume all paused processes.
err = container.Resume()
if err != nil {
log.Fatal(err)
}
// Send signal to container's init process.
err = container.Signal(unix.SIGHUP)
if err != nil {
log.Fatal(err)
}
// Update container resource constraints.
err = container.Set(*config)
if err != nil {
log.Fatal(err)
}
// Get current status of the container.
status, err := container.Status()
if err != nil {
log.Fatal(err)
}
log.Print(status)
// Get current container's state information.
state, err := container.State()
if err != nil {
log.Fatal(err)
}
log.Print(state)
}
Index ¶
- Variables
- type BaseState
- type IO
- type Process
- func (p *Process) Pid() (int, error)
- func (p *Process) Signal(sig os.Signal) error
- func (p *Process) Wait() (*os.ProcessState, error)
- type Status
Examples ¶
Variables ¶
var ( ErrExist = errors.New("container with given ID already exists") ErrInvalidID = errors.New("invalid container ID format") ErrNotExist = errors.New("container does not exist") ErrPaused = errors.New("container paused") ErrRunning = errors.New("container still running") ErrNotRunning = errors.New("container not running") ErrNotPaused = errors.New("container not paused") ErrCgroupNotExist = errors.New("cgroup not exist") )
Types ¶
type BaseState ¶
type BaseState struct {
// ID is the container ID.
ID string `json:"id"`
// InitProcessPid is the init process id in the parent namespace.
InitProcessPid int `json:"init_process_pid"`
// InitProcessStartTime is the init process start time in clock cycles since boot time.
InitProcessStartTime uint64 `json:"init_process_start"`
// Created is the unix timestamp for the creation time of the container in UTC
Created time.Time `json:"created"`
// Config is the container's configuration.
Config configs.Config `json:"config"`
}
BaseState represents the platform agnostic pieces relating to a running container's state
type IO ¶
type IO struct {
Stdin io.WriteCloser
Stdout io.ReadCloser
Stderr io.ReadCloser
}
IO holds the process's STDIO
type Process ¶
type Process struct {
// The command to be run followed by any arguments.
Args []string
// Env specifies the environment variables for the process.
Env []string
// UID and GID of the executing process running inside the container
// local to the container's user and group configuration.
UID, GID int
// AdditionalGroups specifies the gids that should be added to supplementary groups
// in addition to those that the user belongs to.
AdditionalGroups []int
// Cwd will change the process's current working directory inside the container's rootfs.
Cwd string
// Stdin is a reader which provides the standard input stream.
Stdin io.Reader
// Stdout is a writer which receives the standard output stream.
Stdout io.Writer
// Stderr is a writer which receives the standard error stream.
Stderr io.Writer
// ExtraFiles specifies additional open files to be inherited by the process.
ExtraFiles []*os.File
// Initial size for the console.
ConsoleWidth uint16
ConsoleHeight uint16
// Capabilities specify the capabilities to keep when executing the process.
// All capabilities not specified will be dropped from the processes capability mask.
//
// If not nil, takes precedence over container's [configs.Config.Capabilities].
Capabilities *configs.Capabilities
// AppArmorProfile specifies the profile to apply to the process and is
// changed at the time the process is executed.
//
// If not empty, takes precedence over container's [configs.Config.AppArmorProfile].
AppArmorProfile string
// Label specifies the label to apply to the process. It is commonly used by selinux.
//
// If not empty, takes precedence over container's [configs.Config.ProcessLabel].
Label string
// NoNewPrivileges controls whether processes can gain additional privileges.
//
// If not nil, takes precedence over container's [configs.Config.NoNewPrivileges].
NoNewPrivileges *bool
// Rlimits specifies the resource limits, such as max open files, to set for the process.
// If unset, the process will inherit rlimits from the parent process.
//
// If not empty, takes precedence over container's [configs.Config.Rlimit].
Rlimits []configs.Rlimit
// ConsoleSocket provides the masterfd console.
ConsoleSocket *os.File
// PidfdSocket provides process file descriptor of it own.
PidfdSocket *os.File
// Init specifies whether the process is the first process in the container.
Init bool
// LogLevel is a string containing a numeric representation of the current
// log level (i.e. "4", but never "info"). It is passed on to runc init as
// _LIBCONTAINER_LOGLEVEL environment variable.
LogLevel string
// SubCgroupPaths specifies sub-cgroups to run the process in.
// Map keys are controller names, map values are paths (relative to
// container's top-level cgroup).
//
// If empty, the default top-level container's cgroup is used.
//
// For cgroup v2, the only key allowed is "".
SubCgroupPaths map[string]string
// Scheduler represents the scheduling attributes for a process.
//
// If not empty, takes precedence over container's [configs.Config.Scheduler].
Scheduler *configs.Scheduler
// IOPriority is a process I/O priority.
//
// If not empty, takes precedence over container's [configs.Config.IOPriority].
IOPriority *configs.IOPriority
CPUAffinity *configs.CPUAffinity
// contains filtered or unexported fields
}
Process defines the configuration and IO for a process inside a container.
Note that some Process properties are also present in container configuration (configs.Config). In all such cases, Process properties take precedence over container configuration ones.
func (*Process) Pid ¶
Pid returns the process ID
func (*Process) Signal ¶
Signal sends a signal to the Process.
func (*Process) Wait ¶
func (p *Process) Wait() (*os.ProcessState, error)
Wait waits for the process to exit. Wait releases any resources associated with the Process
type Status ¶
type Status int
Status is the status of a container.
const ( // Created is the status that denotes the container exists but has not been run yet. Created Status = iota // Running is the status that denotes the container exists and is running. Running // Paused is the status that denotes the container exists, but all its processes are paused. Paused // Stopped is the status that denotes the container does not have a created or running process. Stopped )
func (Status) String ¶
Source Files ¶
cmd_clone.go container.go env.go error.go process.go restored_process.go sync.go sync_unix.go
Directories ¶
| Path | Synopsis |
|---|---|
| libcontainer/apparmor | Package apparmor provides a minimal set of helpers to configure the AppArmor profile of the current process, effectively acting as a very stripped-down version of libapparmor. |
| libcontainer/capabilities | |
| libcontainer/configs | Package configs provides various container-related configuration types used by libcontainer. |
| libcontainer/configs/validate | Package validate provides helpers for validating configuration. |
| libcontainer/devices | Package devices provides some helper functions for constructing device configurations for runc. |
| libcontainer/exeseal | Package exeseal provides mechanisms for sealing /proc/self/exe and thus protecting the runc binary against CVE-2019-5736-style attacks. |
| libcontainer/integration | Package integration is used for integration testing of libcontainer. |
| libcontainer/intelrdt | |
| libcontainer/internal | |
| libcontainer/keys | Package keys provides helpers for Linux keyrings. |
| libcontainer/logs | Package logs provides helpers for logging used within runc (specifically for forwarding logs from "runc init" to the main runc process). |
| libcontainer/nsenter | |
| libcontainer/nsenter/test | Package escapetest is part of the escape_json_string unit test. |
| libcontainer/seccomp | Package seccomp provides runc-specific helpers for loading and managing seccomp profiles. |
| libcontainer/seccomp/patchbpf | Package patchbpf provides utilities for patching libseccomp-generated cBPF programs in order to handle unknown syscalls and ENOSYS more gracefully. |
| libcontainer/specconv | |
| libcontainer/system | Package system provides wrappers for Linux system operations. |
| libcontainer/utils | Package utils provides general helper utilities used in libcontainer. |
- Version
- v1.5.0-rc.2
- Published
- Apr 3, 2026
- Platform
- js/wasm
- Imports
- 19 packages
- Last checked
- 10 minutes ago –
Tools for package owners.