blog/source/_posts/enable-ubuntu-cgroup2-and-nerdctl.md

91 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 在Ubuntu LTS中启用CGroup v2并安装nerdctl
tags:
- Linux
- 容器化
- Ubuntu
- systemd
- cgroup
categories:
- - DevOps
- 系统管理
keywords: 'ubuntu,containerd,nerdctl,cgroup'
date: 2022-08-04 10:36:50
---
如果云主机采用了Ubuntu 21.04或以下的版本时默认开启的是CGroup v1如果要使容器系统能够使用CGroup v2来管理资源就必须手动开启CGroup v2。本文将记录如何在Ubuntu 21.04及以下系统中开启CGroup v2并安装containerd容器系统和nerdctl容器控制工具的过程。<!-- more -->
## 启动CGroup v2功能
在启动系统的CGroup v2功能之前首先需要确认系统是否提供了CGroup v2的支持并且系统是否已经启动了CGroup v2功能。
在命令行中执行以下命令可以查看系统是否提供了CGroup v2的支持。
```bash
grep cgroup /proc/filesystems
```
如果输出的结果中包含以下内容那就说明系统已经提供了CGroup v2的支持。
```bash
nodev cgroup2
```
接下来是检查系统中是否已经激活了CGroup v2。同样在命令行中执行以下命令
```bash
ls /sys/fs/cgroup/cgroup.controllers
```
如果系统提示找不到指定文件那么就说明系统目前没有激活CGroup v2。
此时就可以激活系统中的CGroup v2了需要注意的是激活系统中的CGroup v2功能会要求系统重新启动如果正在操作生产系统要保证当前系统管理操作不会对系统中所承载的服务产生影响。
打开系统中的`/etc/default/grub/`文件,在其中的`GRUB_CMDLINE_LINUX`参数的尾部增加以下内容。
```text
systemd.unified_cgroup_hierarchy=1
```
添加完以后的`GRUB_CMDLINE_LINUX`参数可能是这样的:
```text
GRUB_CMDLINE_LINUX=" vga=792 console=tty0 console=ttyS0,115200n8 net.ifnames=0 noibrs systemd.unified_cgroup_hierarchy=1"
```
完成添加以后执行以下两条命令,更新系统引导并重新启动系统。
```bash
sudo update-grub
sudo shutdown -r now
```
!!! note ""
如果是使用root用户进行的操作则不必使用`sudo`。
完成系统重启以后可以再次执行检查CGroup v2是否已经激活的命令此时应该会列出`cgroup.controllers`文件。
!!! note ""
执行命令`cat /sys/fs/cgroup/cgroup.controllers`可以检查目前有哪些设备已经托管给了CGroup。
## 安装containerd和nerdctl
containerd是一个OCI标准的容器化支持环境但是并不需要我们单独的去完成containerd的安装。nerdctl的完整安装包内已经集成了containerd、runC和CNI所以直接在Ubuntu中安装nerdctl的完整版即可。
顺序执行以下命令可以下载nerdctl 0.22.2版并将nerdctl和containerd等都安装到`/usr/local`中。
```bash
wget https://ghproxy.com/https://github.com/containerd/nerdctl/releases/download/v0.22.2/nerdctl-full-0.22.2-linux-amd64.tar.gz
tar Cxzvf /usr/local nerdctl-full-0.19.0-linux-amd64.tar.gz
cp /usr/local/lib/systemd/system/*.service /etc/systemd/system/
systemctl enable buildkit containerd
systemctl start buildkit containerd
```
以上命令的最后两行是启动containerd和镜像打包支持。安装包解压完毕以后不必重启系统应该就已经可以执行`nerdctl`命令了。
如果当前不能使用root用户来完成containerd和nerdctl的安装那么就需要使用Rootless方式安装nerdctl了。这种情况下可以执行完上面第二条解压命令以后执行以下命令完成安装。
```bash
containerd-rootless-setuptool.sh install
```