runc
CLI tool for spawning and running containers according to the OCI specification
Top Related Projects
An open and reliable container runtime
The Moby Project - a collaborative project for the container ecosystem to assemble container-based systems
Production-Grade Container Scheduling and Management
:warning: This repository is deprecated and will be archived (Docker CE itself is NOT deprecated) see the https://github.com/docker/docker-ce/blob/master/README.md :warning:
Open Container Initiative-based implementation of Kubernetes Container Runtime Interface
Kata Containers is an open source project and community working to build a standard implementation of lightweight Virtual Machines (VMs) that feel and perform like containers, but provide the workload isolation and security advantages of VMs. https://katacontainers.io/
Quick Overview
runc is a CLI tool for spawning and running containers according to the OCI specification. It's a low-level component used by container runtimes like Docker and Podman, providing a standardized way to create and manage containers on Linux systems.
Pros
- Implements the OCI (Open Container Initiative) runtime specification, ensuring compatibility across different container technologies
- Lightweight and focused on container execution, making it efficient and suitable for various use cases
- Actively maintained by the open-source community and backed by major industry players
- Provides a stable foundation for building higher-level container runtimes and orchestration tools
Cons
- Primarily designed for Linux systems, limiting its use on other operating systems
- Requires root privileges or specific capabilities for many operations, which can be a security concern
- Has a steeper learning curve compared to higher-level container tools like Docker
- Limited built-in features compared to full-fledged container runtimes, as it focuses on core container execution
Getting Started
To get started with runc:
-
Install runc on your Linux system:
sudo apt-get update && sudo apt-get install runc
-
Create an OCI bundle (a directory containing a
config.json
and a root filesystem):mkdir my-container cd my-container runc spec
-
Modify the
config.json
file to suit your needs. -
Run the container:
sudo runc run my-container-id
Note: Using runc directly requires understanding of OCI specifications and container internals. For most use cases, it's recommended to use higher-level tools that leverage runc under the hood.
Competitor Comparisons
An open and reliable container runtime
Pros of containerd
- Higher-level container runtime with more features and functionality
- Designed for integration into larger systems like Kubernetes
- Supports multiple container runtimes, including runc
Cons of containerd
- More complex and resource-intensive than runc
- Steeper learning curve for basic container operations
Code comparison
runc (low-level container runtime):
spec, err := loadSpec(context.Background(), specConfig)
if err != nil {
return err
}
status, err := startContainer(context.Background(), spec, opts)
containerd (high-level container runtime):
client, err := containerd.New("/run/containerd/containerd.sock")
container, err := client.NewContainer(ctx, "example")
task, err := container.NewTask(ctx, cio.NewCreator(cio.WithStdio))
err = task.Start(ctx)
The code snippets illustrate the difference in abstraction levels. runc operates directly with container specifications, while containerd provides a higher-level API for managing containers, tasks, and images.
containerd offers more comprehensive container management capabilities, making it suitable for complex orchestration systems. However, this comes at the cost of increased complexity and resource usage compared to the simpler runc.
runc remains an excellent choice for basic container operations and when lightweight, low-level control is required. containerd is better suited for more advanced use cases and integration with larger container ecosystems.
The Moby Project - a collaborative project for the container ecosystem to assemble container-based systems
Pros of Moby
- More comprehensive container ecosystem, including image building and management
- Extensive API and CLI for container operations
- Larger community and ecosystem of tools and plugins
Cons of Moby
- Heavier and more complex than runc
- Steeper learning curve for beginners
- May include features not needed for simple container deployments
Code Comparison
Moby (Docker Engine) container creation:
cli, err := client.NewClientWithOpts(client.FromEnv)
resp, err := cli.ContainerCreate(ctx, &container.Config{
Image: "alpine",
Cmd: []string{"echo", "hello world"},
}, nil, nil, nil, "")
runc container creation:
spec, err := generate.New("linux")
spec.Process.Args = []string{"/bin/sh", "-c", "echo hello world"}
err = spec.Save(specConfig, "config.json")
cmd := exec.Command("runc", "run", "mycontainer")
Both projects aim to manage containers, but Moby provides a higher-level abstraction with more features, while runc focuses on the core container runtime. Moby is better suited for complex container orchestration, while runc is ideal for lightweight, low-level container management.
Production-Grade Container Scheduling and Management
Pros of Kubernetes
- Comprehensive container orchestration platform for managing large-scale deployments
- Rich ecosystem with extensive tooling and community support
- Built-in features for scaling, load balancing, and self-healing
Cons of Kubernetes
- Steeper learning curve and more complex setup compared to runc
- Higher resource overhead for small-scale deployments
- Requires additional components and services to function fully
Code Comparison
runc (basic container run command):
runc run mycontainer
Kubernetes (pod deployment):
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myimage:latest
Summary
runc is a lightweight, low-level container runtime that focuses on running containers according to the OCI specification. It's ideal for simple container execution and is often used as a building block for more complex container management systems.
Kubernetes, on the other hand, is a full-fledged container orchestration platform that provides a wide range of features for managing containerized applications at scale. While it offers more functionality and flexibility, it also comes with increased complexity and resource requirements.
The choice between runc and Kubernetes depends on the specific needs of the project, with runc being suitable for basic container operations and Kubernetes excelling in large-scale, distributed environments.
:warning: This repository is deprecated and will be archived (Docker CE itself is NOT deprecated) see the https://github.com/docker/docker-ce/blob/master/README.md :warning:
Pros of docker-ce
- More comprehensive container management solution, including image building and orchestration
- User-friendly CLI and GUI interfaces for easier container management
- Extensive documentation and community support
Cons of docker-ce
- Larger footprint and more resource-intensive compared to runc
- More complex architecture, potentially introducing additional points of failure
- Less flexibility for customization in low-level container operations
Code Comparison
runc:
func (r *Runc) Create(context context.Context, id, bundle string, opts *CreateOpts) error {
args := []string{"create", "--bundle", bundle}
if opts != nil {
args = append(args, opts.Args...)
}
cmd := r.command(context, append(args, id)...)
return runOrError(cmd)
}
docker-ce:
func (cli *DockerCli) CmdCreate(args ...string) error {
cmd := cli.Subcmd("create", []string{"IMAGE [COMMAND] [ARG...]"}, dockerCmdHelpTemplate, false)
// ... (omitted for brevity)
return cli.createContainer(config, hostConfig, networkingConfig, containerName)
}
The code snippets demonstrate that runc focuses on low-level container creation, while docker-ce provides a higher-level abstraction with additional features and options for container management.
Open Container Initiative-based implementation of Kubernetes Container Runtime Interface
Pros of cri-o
- Designed specifically for Kubernetes, offering better integration and performance
- Supports multiple container runtimes, including runc
- Implements CRI (Container Runtime Interface) natively, simplifying Kubernetes integration
Cons of cri-o
- More complex setup and configuration compared to runc
- Limited use cases outside of Kubernetes environments
- Steeper learning curve for developers familiar with Docker
Code Comparison
cri-o (Go):
func (s *Server) CreateContainer(ctx context.Context, req *pb.CreateContainerRequest) (*pb.CreateContainerResponse, error) {
// Container creation logic
}
runc (Go):
func (r *Runc) Create(context context.Context, id, bundle string, opts *CreateOpts) error {
// Container creation logic
}
Both projects use Go and provide container creation functionality, but cri-o's implementation is more focused on Kubernetes integration, while runc offers a lower-level container runtime interface.
Kata Containers is an open source project and community working to build a standard implementation of lightweight Virtual Machines (VMs) that feel and perform like containers, but provide the workload isolation and security advantages of VMs. https://katacontainers.io/
Pros of kata-containers
- Enhanced security through hardware-assisted isolation
- Better compatibility with legacy applications
- Improved resource utilization and density
Cons of kata-containers
- Higher resource overhead compared to runc
- Increased complexity in setup and management
- Potentially slower startup times
Code comparison
runc:
func (r *Runc) Create(context context.Context, id, bundle string, opts *CreateOpts) error {
args := []string{"create", "--bundle", bundle}
if opts != nil {
args = append(args, opts.AdditionalArgs...)
}
cmd := r.command(context, append(args, id)...)
return r.runOrError(cmd)
}
kata-containers:
func (k *kataAgent) createContainer(ctx context.Context, sandboxID string, c *Container) (*Process, error) {
span, ctx := k.trace(ctx, "createContainer")
defer span.End()
createContainer := &grpc.CreateContainerRequest{
ContainerId: c.id,
ExecId: c.id,
Storages: k.getStorages(c.mounts),
OCI: &grpc.Spec{Annotations: c.config.Annotations},
}
_, err := k.sendReq(ctx, createContainer)
if err != nil {
return nil, err
}
return buildProcessFromGrpc(c.id, c.id), nil
}
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
runc
Introduction
runc
is a CLI tool for spawning and running containers on Linux according to the OCI specification.
Releases
You can find official releases of runc
on the release page.
All releases are signed by one of the keys listed in the runc.keyring
file in the root of this repository.
Security
The reporting process and disclosure communications are outlined here.
Security Audit
A third party security audit was performed by Cure53, you can see the full report here.
Building
runc
only supports Linux. It must be built with Go version 1.21 or higher.
Pre-Requisites
Go
NOTE: if building with Go 1.22.x, make sure to use 1.22.4 or a later version (see issue #4233 for more details).
Utilities and Libraries
In addition to Go, building runc
requires multiple utilities and libraries to be installed on your system.
On Ubuntu/Debian, you can install the required dependencies with:
apt update && apt install -y make gcc linux-libc-dev libseccomp-dev pkg-config git
On CentOS/Fedora, you can install the required dependencies with:
yum install -y make gcc kernel-headers libseccomp-devel pkg-config git
On Alpine Linux, you can install the required dependencies with:
apk --update add bash make gcc libseccomp-dev musl-dev linux-headers git
The following dependencies are optional:
libseccomp
- only required if you enable seccomp support; to disable, see Build Tags
Build
# create a 'github.com/opencontainers' in your GOPATH/src
cd github.com/opencontainers
git clone https://github.com/opencontainers/runc
cd runc
make
sudo make install
You can also use go get
to install to your GOPATH
, assuming that you have a github.com
parent folder already created under src
:
go get github.com/opencontainers/runc
cd $GOPATH/src/github.com/opencontainers/runc
make
sudo make install
runc
will be installed to /usr/local/sbin/runc
on your system.
Version string customization
You can see the runc version by running runc --version
. You can append a custom string to the
version using the EXTRA_VERSION
make variable when building, e.g.:
make EXTRA_VERSION="+build-1"
Bear in mind to include some separator for readability.
Build Tags
runc
supports optional build tags for compiling support of various features,
with some of them enabled by default (see BUILDTAGS
in top-level Makefile
).
To change build tags from the default, set the BUILDTAGS
variable for make,
e.g. to disable seccomp:
make BUILDTAGS=""
Build Tag | Feature | Enabled by Default | Dependencies |
---|---|---|---|
seccomp | Syscall filtering using libseccomp . | yes | libseccomp |
!runc_nodmz | Reduce memory usage for CVE-2019-5736 protection by using a small C binary, see memfd-bind for more details. runc_nodmz disables this experimental feature and causes runc to use a different protection mechanism which will further increases memory usage temporarily during container startup. To enable this feature you also need to set the RUNC_DMZ=true environment variable. | yes |
The following build tags were used earlier, but are now obsoleted:
- nokmem (since runc v1.0.0-rc94 kernel memory settings are ignored)
- apparmor (since runc v1.0.0-rc93 the feature is always enabled)
- selinux (since runc v1.0.0-rc93 the feature is always enabled)
Running the test suite
runc
currently supports running its test suite via Docker.
To run the suite just type make test
.
make test
There are additional make targets for running the tests outside of a container but this is not recommended as the tests are written with the expectation that they can write and remove anywhere.
You can run a specific test case by setting the TESTFLAGS
variable.
# make test TESTFLAGS="-run=SomeTestFunction"
You can run a specific integration test by setting the TESTPATH
variable.
# make test TESTPATH="/checkpoint.bats"
You can run a specific rootless integration test by setting the ROOTLESS_TESTPATH
variable.
# make test ROOTLESS_TESTPATH="/checkpoint.bats"
You can run a test using your container engine's flags by setting CONTAINER_ENGINE_BUILD_FLAGS
and CONTAINER_ENGINE_RUN_FLAGS
variables.
# make test CONTAINER_ENGINE_BUILD_FLAGS="--build-arg http_proxy=http://yourproxy/" CONTAINER_ENGINE_RUN_FLAGS="-e http_proxy=http://yourproxy/"
Go Dependencies Management
runc
uses Go Modules for dependencies management.
Please refer to Go Modules for how to add or update
new dependencies.
# Update vendored dependencies
make vendor
# Verify all dependencies
make verify-dependencies
Using runc
Please note that runc is a low level tool not designed with an end user in mind. It is mostly employed by other higher level container software.
Therefore, unless there is some specific use case that prevents the use of tools like Docker or Podman, it is not recommended to use runc directly.
If you still want to use runc, here's how.
Creating an OCI Bundle
In order to use runc you must have your container in the format of an OCI bundle.
If you have Docker installed you can use its export
method to acquire a root filesystem from an existing Docker container.
# create the top most bundle directory
mkdir /mycontainer
cd /mycontainer
# create the rootfs directory
mkdir rootfs
# export busybox via Docker into the rootfs directory
docker export $(docker create busybox) | tar -C rootfs -xvf -
After a root filesystem is populated you just generate a spec in the format of a config.json
file inside your bundle.
runc
provides a spec
command to generate a base template spec that you are then able to edit.
To find features and documentation for fields in the spec please refer to the specs repository.
runc spec
Running Containers
Assuming you have an OCI bundle from the previous step you can execute the container in two different ways.
The first way is to use the convenience command run
that will handle creating, starting, and deleting the container after it exits.
# run as root
cd /mycontainer
runc run mycontainerid
If you used the unmodified runc spec
template this should give you a sh
session inside the container.
The second way to start a container is using the specs lifecycle operations.
This gives you more power over how the container is created and managed while it is running.
This will also launch the container in the background so you will have to edit
the config.json
to remove the terminal
setting for the simple examples
below (see more details about runc terminal handling).
Your process field in the config.json
should look like this below with "terminal": false
and "args": ["sleep", "5"]
.
"process": {
"terminal": false,
"user": {
"uid": 0,
"gid": 0
},
"args": [
"sleep", "5"
],
"env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"TERM=xterm"
],
"cwd": "/",
"capabilities": {
"bounding": [
"CAP_AUDIT_WRITE",
"CAP_KILL",
"CAP_NET_BIND_SERVICE"
],
"effective": [
"CAP_AUDIT_WRITE",
"CAP_KILL",
"CAP_NET_BIND_SERVICE"
],
"inheritable": [
"CAP_AUDIT_WRITE",
"CAP_KILL",
"CAP_NET_BIND_SERVICE"
],
"permitted": [
"CAP_AUDIT_WRITE",
"CAP_KILL",
"CAP_NET_BIND_SERVICE"
],
"ambient": [
"CAP_AUDIT_WRITE",
"CAP_KILL",
"CAP_NET_BIND_SERVICE"
]
},
"rlimits": [
{
"type": "RLIMIT_NOFILE",
"hard": 1024,
"soft": 1024
}
],
"noNewPrivileges": true
},
Now we can go through the lifecycle operations in your shell.
# run as root
cd /mycontainer
runc create mycontainerid
# view the container is created and in the "created" state
runc list
# start the process inside the container
runc start mycontainerid
# after 5 seconds view that the container has exited and is now in the stopped state
runc list
# now delete the container
runc delete mycontainerid
This allows higher level systems to augment the containers creation logic with setup of various settings after the container is created and/or before it is deleted. For example, the container's network stack is commonly set up after create
but before start
.
Rootless containers
runc
has the ability to run containers without root privileges. This is called rootless
. You need to pass some parameters to runc
in order to run rootless containers. See below and compare with the previous version.
Note: In order to use this feature, "User Namespaces" must be compiled and enabled in your kernel. There are various ways to do this depending on your distribution:
- Confirm
CONFIG_USER_NS=y
is set in your kernel configuration (normally found in/proc/config.gz
) - Arch/Debian:
echo 1 > /proc/sys/kernel/unprivileged_userns_clone
- RHEL/CentOS 7:
echo 28633 > /proc/sys/user/max_user_namespaces
Run the following commands as an ordinary user:
# Same as the first example
mkdir ~/mycontainer
cd ~/mycontainer
mkdir rootfs
docker export $(docker create busybox) | tar -C rootfs -xvf -
# The --rootless parameter instructs runc spec to generate a configuration for a rootless container, which will allow you to run the container as a non-root user.
runc spec --rootless
# The --root parameter tells runc where to store the container state. It must be writable by the user.
runc --root /tmp/runc run mycontainerid
Supervisors
runc
can be used with process supervisors and init systems to ensure that containers are restarted when they exit.
An example systemd unit file looks something like this.
[Unit]
Description=Start My Container
[Service]
Type=forking
ExecStart=/usr/local/sbin/runc run -d --pid-file /run/mycontainerid.pid mycontainerid
ExecStopPost=/usr/local/sbin/runc delete mycontainerid
WorkingDirectory=/mycontainer
PIDFile=/run/mycontainerid.pid
[Install]
WantedBy=multi-user.target
More documentation
- Spec conformance
- cgroup v2
- Checkpoint and restore
- systemd cgroup driver
- Terminals and standard IO
- Experimental features
License
The code and docs are released under the Apache 2.0 license.
Top Related Projects
An open and reliable container runtime
The Moby Project - a collaborative project for the container ecosystem to assemble container-based systems
Production-Grade Container Scheduling and Management
:warning: This repository is deprecated and will be archived (Docker CE itself is NOT deprecated) see the https://github.com/docker/docker-ce/blob/master/README.md :warning:
Open Container Initiative-based implementation of Kubernetes Container Runtime Interface
Kata Containers is an open source project and community working to build a standard implementation of lightweight Virtual Machines (VMs) that feel and perform like containers, but provide the workload isolation and security advantages of VMs. https://katacontainers.io/
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot