LXD

From Funtoo
Revision as of 22:36, June 15, 2022 by FuzzyBot (talk | contribs) (Updating to match new version of source page)
Jump to navigation Jump to search
Other languages:
English • ‎português do Brasil • ‎中文(中国大陆)‎

Introdução

   Important

Please note that if you plan to use LXD on a laptop, you are likely using WiFi and NetworkManager, and the steps below will not work for you bridge setup. Please see LXD/Laptop Network Setup for important differences to allow you to use LXD in 'dev mode' for local use of containers for development.

O LXD é um "hypervisor" de contêineres projetado para fornecer um conjunto fácil de ferramentas para gerenciar contêineres Linux, e atualmente seu desenvolvimento está sendo liderado por funcionários da Canonical. Você pode aprender mais sobre o projeto em geral em https://linuxcontainers.org/lxd/ .

Atualmente, o LXD é usado para infraestrutura de contêineres para Funtoo Containers e também é muito bem suportado no Funtoo Linux. Por esse motivo, é recomendável que você verifique o LXD e veja o que ele pode fazer por você.

Configuração básica no Funtoo

As etapas a seguir mostrarão como configurar um ambiente LXD básico no Funtoo Linux. Esse ambiente basicamente usa a configuração padrão do LXD - e será chamada de lxdbr0, e usará o NAT para fornecer acesso à Internet aos seus contêineres. Além disso, será criado um pool de armazenamento padrão que simplesmente usará o armazenamento do sistema de arquivos existente, criando um diretório em /var/lib/lxd/storage-pools/default para armazenar os contêineres criados. São possíveis configurações mais sofisticadas que usam pontes de rede dedicadas conectadas a interfaces físicas sem NAT, bem como pools de armazenamento dedicados que usam ZFS e BTRFS - no entanto, esses tipos de configurações geralmente são um exagero para uma estação de trabalho do desenvolvedor e devem ser tentados apenas por usuários avançados. Portanto, não os cobriremos aqui.

Requerimentos

This section will guide you through setting up the basic requirements for creating an LXD environment.

O primeiro passo é surgir o LXD e suas dependências. Faça o seguinte:

root # emerge -a lxd

Quando o LXD terminar de emergir, desejamos permitir que ele inicie por padrão:

root # rc-update add lxd default

Além disso, queremos configurar os seguintes arquivos. O /etc/security/limits.conf deve ser modificado para ter as seguintes linhas:

   /etc/security/limits.conf
*       soft    nofile  1048576
*       hard    nofile  1048576
root    soft    nofile  1048576
root    hard    nofile  1048576
*       soft    memlock unlimited
*       hard    memlock unlimited
# End of file

Além disso, queremos mapear um conjunto de IDs de usuário e de grupo para o usuário raiz, para que estejam disponíveis para seu uso. Faça isso criando os arquivos /etc/subuid e /etc/subgid com o seguinte conteúdo idêntico:

   Note

This should not be necessary to set anymore, as by default, LXD should default to a subuid/subgid range 10x bigger than this by default. See https://linuxcontainers.org/lxd/docs/master/userns-idmap

   /etc/subuid
root:1000000:1000000000
   /etc/subgid
root:1000000:1000000000

Neste ponto, estamos prontos para inicializar e iniciar o LXD.

Inicialização

Para configurar o LXD, primeiro precisaremos iniciar o LXD. Isso pode ser feito da seguinte forma:

root # /etc/init.d/lxd start

Neste ponto, podemos executar o lxd init para executar um assistente de configuração para configurar o LXD:

root # lxd init
Would you like to use LXD clustering? (yes/no) [default=no]: 
Do you want to configure a new storage pool? (yes/no) [default=yes]: 
Name of the new storage pool [default=default]: 
Name of the storage backend to use (btrfs, dir, lvm) [default=btrfs]: dir ↵
Would you like to connect to a MAAS server? (yes/no) [default=no]: 
Would you like to create a new local network bridge? (yes/no) [default=yes]: 
What should the new bridge be called? [default=lxdbr0]: 
What IPv4 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: 
What IPv6 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: none ↵
Would you like LXD to be available over the network? (yes/no) [default=no]: 
Would you like stale cached images to be updated automatically? (yes/no) [default=yes] 
Would you like a YAML "lxd init" preseed to be printed? (yes/no) [default=no]: 
root #

Como você pode ver, escolhemos todas as opções padrão 'exceto' para o pool de armazenamento, onde optamos por usar um diretório baseado em armazenamento contêiner em vez de BTRFS. Agora, devemos poder executar a lxc image list e obter uma resposta do daemon LXD:

   Warning

As explained above, turn off IPv6 NAT in LXD unless you specifically intend to use it! It can confuse dhcpcd.

If you choose to output the YAML lxd init preseed configuration from the lxd init command above, here is a config example:

   lxc_init_preseed.yaml (YAML source code) - lxc init preseed config example
config:
  images.auto_update_interval: "0"
networks:
- config:
    ipv4.address: auto
    ipv6.address: none
  description: ""
  name: lxdbr0
  type: ""
  project: default
storage_pools:
- config: {}
  description: ""
  name: default
  driver: dir
profiles:
- config: {}
  description: ""
  devices:
    eth0:
      name: eth0
      network: lxdbr0
      type: nic
    root:
      path: /
      pool: funtoo
      type: disk
  name: default
projects: []
cluster: null

Now, we should be able to run lxc image list and get a response from the LXD daemon:

root # lxc image list
+-------+-------------+--------+-------------+------+------+-------------+
| ALIAS | FINGERPRINT | PUBLIC | DESCRIPTION | ARCH | SIZE | UPLOAD DATE |
+-------+-------------+--------+-------------+------+------+-------------+
root #

Se você é capaz de fazer isso, configurou com êxito as partes principais do LXD! Observe que usamos o comando lxc e não lxd como fizemos no lxd init - a partir deste momento, você usará o lxc Não deixe que isso confunda você - o comando lxc é a principal ferramenta de linha de comando para trabalhar com contêineres LXD.

Acima, você pode ver que nenhuma imagem está instalada. Imagens são instantâneos instaláveis de contêineres que podemos usar para criar novos contêineres. Então, como primeiro passo, vamos em frente e pegue uma imagem que possamos usar. Você deseja procurar em https://build.funtoo.org em busca de uma imagem LXD que funcione no hardware do seu computador. Por exemplo, eu consegui baixar o seguinte arquivo usando o wget:

root # wget https://build.funtoo.org/1.4-release-std/x86-64bit/amd64-zen2/2022-04-13/lxd-amd64-zen2-1.4-release-std-2022-04-13.tar.xz

Uma vez baixada, esta imagem pode ser instalada usando o seguinte comando:

root # lxc image import lxd-amd64-zen2-1.4-release-std-2022-04-13.tar.xz --alias funtoo
Image imported with fingerprint: fe4d27fb31bfaf3bd4f470e0ea43d26a6c05991de2a504b9e0a3b1a266dddc69

Agora você verá a imagem disponível em nossa lista de imagens:

root # lxc image list
+--------+--------------+--------+-----------------------------------------+--------------+-----------+----------+------------------------------+

Primeiro container

Agora é hora de lançar nosso primeiro contêiner. Isso pode ser feito da seguinte forma:

root # lxc launch funtoo testcontainer
Creating testcontainer
Starting testcontainer

Agora podemos ver o contêiner sendo executado via lxc list:

root # lxc list
+---------------+---------+------+-----------------------------------------------+------------+-----------+
| NAME          |  STATE  | IPV4 |                     IPV6                      |    TYPE    | SNAPSHOTS |
+---------------+---------+------+-----------------------------------------------+------------+-----------+
| testcontainer | RUNNING |      | fd42:8063:81cb:988c:216:3eff:fe2a:f901 (eth0) | PERSISTENT |           |
+---------------+---------+------+-----------------------------------------------+------------+-----------+
root #

Por padrão, nosso novo contêiner testcontainer usará o perfil padrão, que conectará uma interface eth0 no contêiner ao NAT e também usará nosso pool de armazenamento LXD baseado em diretório. Agora podemos entrar no contêiner da seguinte maneira:

root # lxc exec testcontainer -- su --login
testcontainer #

Como você deve ter notado, ainda não temos nenhuma rede IPv4 configurada. Embora o LXD tenha configurado uma ponte e um NAT para nós, juntamente com um servidor DHCP para consulta, na verdade, precisamos usar o dhcpcd para procurar um endereço IP, então vamos configurá-lo:

testcontainer # echo "template=dhcpcd" > /etc/conf.d/netif.eth0
testcontainer # cd /etc/init.d
testcontainer # ln -s netif.tmpl netif.eth0
testcontainer # rc-update add netif.eth0 default
 * service netif.eth0 added to runlevel default
testcontainer # rc
 * rc is deprecated, please use openrc instead.
 * Caching service dependencies ...                             [ ok ]
 * Starting DHCP Client Daemon ...                              [ ok ]
 * Network dhcpcd eth0 up ...                                   [ ok ]
testcontainer # 

Agora você pode ver que eth0 tem um endereço IPv4 válido:

testcontainer # ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.212.194.17  netmask 255.255.255.0  broadcast 10.212.194.255
        inet6 fd42:8063:81cb:988c:25ea:b5bd:603d:8b0d  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::216:3eff:fe2a:f901  prefixlen 64  scopeid 0x20<link>
        ether 00:16:3e:2a:f9:01  txqueuelen 1000  (Ethernet)
        RX packets 45  bytes 5385 (5.2 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 20  bytes 2232 (2.1 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

What happened is that LXD set up a DHCP server for us (dnsmasq) running on our private container network, and automatically offers IP addresses to our containers. It also configured iptables for us to NAT the connection so that outbound Internet access should magically work. You should also be able to see this IPv4 address listed in the container list when you type lxc list on your host system.

Network Troubleshooting

   Warning

Proceed with caution. These are advanced LXC commands that can modify the state of your LXD local network setup. In extreme scenarios, all of your LXD containers' networks NAT routing can easily break all if the wrong LXC config key value is changed

Note that if you are having issues with your container getting an IPv4 address via DHCP, make sure that you turn IPv6 off in LXD. Do this by running:

root # lxc network edit lxdbr0

Then, change ipv6.nat YAML key value to "false" and restart LXD and the test container:

root # /etc/init.d/lxd restart
root # lxc restart testcontainer

This should resolve the issue.

   Important

If you have initialized your LXD cluster by turning off IPv6 with the What IPv6 address should be used? option set to none, then the ipv6.nat will not even be present in our LXC local network's lxdbr0 bridge interface.

Be careful not to tamper with the ipv4.nat setting or all LXD container NAT routing will break, meaning no network traffic within running and new LXD containers will be able to route to external to the Internet!

Here is some example YAML of a default lxdbr0 LXC local network bridge device for reference:

   lxc_lxdbr0.yaml (YAML source code) - lxc network edit lxdbr0
config:
  ipv4.address: 10.239.139.1/24
  ipv4.nat: "true"
  ipv6.address: none
description: ""
name: lxdbr0
type: bridge
used_by:
- /1.0/profiles/default
- /1.0/instances/funtoo-livestream
managed: true
status: Created
locations:
- none

Finishing Steps

Hora de ter alguma diversão!

testcontainer # ego sync
Syncing meta-repo
Cloning into '/var/git/meta-repo'...