lxc 容器 使用

Last modified date

参考:https://www.cnblogs.com/xidongyu/p/8059781.html

安装 lxc

使用apt命令就可以安装lxc

sudo apt install lxc

创建容器

# sudo lxc-create -t download --name ubuntu1

下面是输出信息
Setting up the GPG keyring
Downloading the image index              <-下载所有支持的Linux发行版列表

---
DIST RELEASE	ARCH	VARIANT	BUILD
ubuntu	xenial	amd64	default	20171214_04:09
[...]
alpine	3.4	amd64	default	20171213_17:50
[...]
centos	6	amd64	default	20171214_02:16
[...]
debian	buster	amd64	default	20171214_04:09
[...]
---

Distribution: ubuntu       <- 这里需要输入操作系统(上面列表中的),我们选择ubuntu
Release: xenial 		  <- 选择操作系统发行版本(上面列表中有的)
Architecture: amd64     <- 选择架构,这里选择64位

Downloading the image index
Downloading the rootfs
Downloading the metadata
The image cache is now ready
Unpacking the rootfs

---
You just created an Ubuntu container (release=xenial, arch=amd64, variant=default)
For security reason, container images ship without user accounts
and without a root password.

Use lxc-attach or chroot directly into the rootfs to set a root password
or create user accounts.

列出现有容器

简单列出
# sudo lxc-ls

详细列出
# sudo lxc-ls --fancy

查看容器信息

# sudo lxc-info --name ubuntu1

启动和关闭容器

# sudo lxc-start --name ubuntu1

以服务的形式启动容器
# sudo lxc-start --name ubuntu1 --daemon

# sudo lxc-stop --name ubuntu1

进入容器

进入容器的方式又三种:

  • lxc-attach命令
  • lxc-console命令
  • 用SSH
进入容器
# sudo lxc-attach --name ubuntu1
让容器执行某个命令(重启ssh服务)
# sudo lxc-attach --name ubuntu1 -- restart ssh

提升特权,并指定名字空间,这个命令在测试主机上软件时很有用
# sudo lxc-attach -name ubuntu1 -e -s 'NETWORK|UTSNAME'
登录容器,需要输入用户名和密码
# sodu lxc-consloe --name ubuntu1
使用SSH登录
# ssh 用户名@IP

容器的删除

先停掉容器然后进行删除
# sudo lxc-stop --name ubuntu1
# sudo lxc-destroy --name ubuntu1

使用固定IP

默认情况下,容器的IP地址是动态分配的.如果要给容器设置固定IP地址,可以修改容器的配置文件.这里以修改普通容器的配置文件为例.

编辑文件
# $ vim ~/.local/share/lxc/ubuntu1/config
$ vim /var/lib/lxc/mycontainer/config
添加固定ip
...
lxc.network.type = veth                                                              
lxc.network.link = lxcbr0                                                            
lxc.network.ipv4 = 10.0.3.102
...

检查 veth 设备状态

LXC 容器通过 veth虚拟网卡连接到网桥,需确保 veth设备正常:

# 查看宿主机上的 veth 设备:
ip link show | grep veth
# 确认 veth 设备状态为 UP:
# 若 veth 设备状态是 DOWN,需启动它:
ip link set vethX up  # 替换 vethX 为实际设备名

滑稽的菊花