Difference between revisions of "LXD/pt-br"

From Funtoo
Jump to navigation Jump to search
(Created page with "==== Listando contêineres ====")
(Updating to match new version of source page)
(38 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages/>
<languages/>
{{Subpages|GPU Acceleration}}
{{Subpages|Laptop Network Setup,GPU Acceleration,GPU Acceleration (NVIDIA),What are subuids and subgids?,Administration Tutorial,Features and Concepts}}
== Introdução ==
== Introdução ==


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/ .  
{{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.}}
 
<div class="mw-translate-fuzzy">
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/ .
</div>


Atualmente, o LXD é usado para infraestrutura de contêineres para [[Special: MyLanguage/Funtoo Containers|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ê.
Atualmente, o LXD é usado para infraestrutura de contêineres para [[Special: MyLanguage/Funtoo Containers|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ê.
Line 9: Line 13:
== Configuração básica no Funtoo ==
== Configuração básica no Funtoo ==


<div class="mw-translate-fuzzy">
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 {{c | 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 {{f|/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 [[Especial: MyLanguage/ZFS|ZFS]] e [[Especial: MyLanguage/BTRFS|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.
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 {{c | 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 {{f|/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 [[Especial: MyLanguage/ZFS|ZFS]] e [[Especial: MyLanguage/BTRFS|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.
</div>


=== Requerimentos ===
=== Requerimentos ===


Esta seção o guiará na configuração dos requisitos básicos para a criação de um ambiente LXD.
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:
O primeiro passo é surgir o LXD e suas dependências. Faça o seguinte:
Line 39: Line 45:
}}
}}


<div class="mw-translate-fuzzy">
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 {{f |/etc/subuid}} e {{f|/etc/subgid}} com o seguinte conteúdo idêntico:
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 {{f |/etc/subuid}} e {{f|/etc/subgid}} com o seguinte conteúdo idêntico:
</div>


{{file|name=/etc/subuid|body=
{{file|name=/etc/subuid|body=
root:100000:1000000000
root:1000000:10000000000
}}
}}


{{file|name=/etc/subgid|body=
{{file|name=/etc/subgid|body=
root:100000:1000000000
root:1000000:10000000000
}}
}}


<div class="mw-translate-fuzzy">
Neste ponto, estamos prontos para inicializar e iniciar o LXD.
Neste ponto, estamos prontos para inicializar e iniciar o LXD.
</div>
==== LXD-in-LXD ====


The only time you will now need to set {{f|/etc/subuid}} and {{f|/etc/subgid}} now is if you are running "LXD-in-LXD". In this case, the inner LXD (within the container) will need to reduce these
subuid and subgid mappings as the full range will not be available. This should be possible by simply using the following settings within your containerized LXD instance:
{{file|name=/etc/subuid|body=
root:65537:70000
}}
{{file|name=/etc/subgid|body=
root:65537:70000
}}
If you are not using advanced features of LXD, your LXD-in-LXD instance should now have sufficient id mappings to isolate container-containers from the host-container. The only remaining
step for LXD-in-LXD would be to allow the host-container to nest:
{{console|body=
# ##i##lxc config set host-container security.nesting true
}}
This will allow for host-container contain containers itself :)


=== Inicialização ===
=== Inicialização ===
Line 67: Line 98:
Do you want to configure a new storage pool? (yes/no) [default=yes]: ##i##↵
Do you want to configure a new storage pool? (yes/no) [default=yes]: ##i##↵
Name of the new storage pool [default=default]: ##i##↵
Name of the new storage pool [default=default]: ##i##↵
Name of the storage backend to use (btrfs, dir, lvm) [default=btrfs]: ##i##dir↵
Name of the storage backend to use (btrfs, dir, lvm) [default=btrfs]: ##i##dir ↵
Would you like to connect to a MAAS server? (yes/no) [default=no]: ##i##↵
Would you like to connect to a MAAS server? (yes/no) [default=no]: ##i##↵
Would you like to create a new local network bridge? (yes/no) [default=yes]: ##i##↵
Would you like to create a new local network bridge? (yes/no) [default=yes]: ##i##↵
What should the new bridge be called? [default=lxdbr0]: ##i##↵
What should the new bridge be called? [default=lxdbr0]: ##i##↵
What IPv4 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: ##i##↵
What IPv4 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: ##i##↵
What IPv6 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: ##i##↵
What IPv6 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: ##i##none
Would you like LXD to be available over the network? (yes/no) [default=no]: ##i##↵
Would you like LXD to be available over the network? (yes/no) [default=no]: ##i##↵
Would you like stale cached images to be updated automatically? (yes/no) [default=yes] ##i##↵
Would you like stale cached images to be updated automatically? (yes/no) [default=yes] ##i##↵
Line 79: Line 110:
}}
}}


<div class="mw-translate-fuzzy">
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  [[Especial: MyLanguage / BTRFS | BTRFS]]. Agora, devemos poder executar a {{c |lxc image list}} e obter uma resposta do daemon LXD:
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  [[Especial: MyLanguage / BTRFS | BTRFS]]. Agora, devemos poder executar a {{c |lxc image list}} e obter uma resposta do daemon LXD:
</div>
{{Warning|As explained above, turn off IPv6 NAT in LXD unless you specifically intend to use it! It can confuse {{c|dhcpcd}}.}}
If you choose to output the ''YAML lxd init preseed'' configuration from the {{c|lxd init}} command above, here is a config example:
{{file|name=lxc_init_preseed.yaml|lang=YAML|desc=lxc init preseed config example|body=
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 {{c|lxc image list}} and get a response from the LXD daemon:


{{console|body=
{{console|body=
# ##i##lxc image list
# ##i##lxc image list
+-------+-------------+--------+-------------+------+------+-------------+
+-------+-------------+--------+-------------+------+------+-------------+
{{!}}
{{!}} ALIAS {{!}} FINGERPRINT {{!}} PUBLIC {{!}} DESCRIPTION {{!}} ARCH {{!}} SIZE {{!}} UPLOAD DATE {{!}}
ALIAS {{!}} FINGERPRINT {{!}} PUBLIC {{!}} DESCRIPTION {{!}} ARCH {{!}} SIZE {{!}} UPLOAD DATE {{!}}
+-------+-------------+--------+-------------+------+------+-------------+
+-------+-------------+--------+-------------+------+------+-------------+
#
#
}}
}}
 
Se você é capaz de fazer isso, configurou com êxito as partes principais do LXD! Observe que usamos o comando {{c | lxc}} e não {{c | lxd}} como fizemos no {{c | lxd init}} - a partir deste momento, você usará o {{c | lxc }} Não deixe que isso confunda você - o comando {{c | lxc}} é a principal ferramenta de linha de comando para trabalhar com contêineres LXD.
Se você é capaz de fazer isso, configurou com êxito as partes principais do LXD! Observe que usamos o comando {{c | lxc}} e não {{c | lxd}} como fizemos no {{c | lxd init}} - a partir deste momento, você usará o {{c | lxc }} Não deixe que isso confunda você - o comando {{c | lxc}} é a principal ferramenta de linha de comando para trabalhar com contêineres LXD.


Line 95: Line 166:


{{console|body=
{{console|body=
# ##i##wget https://build.funtoo.org/1.3-release-std/x86-64bit/intel64-skylake/lxd-intel64-skylake-1.3-release-std-2019-06-11.tar.xz
# ##i##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:
Uma vez baixada, esta imagem pode ser instalada usando o seguinte comando:
{{console|body=
{{console|body=
# ##i##lxc image import lxd-intel64-skylake-1.3-release-std-2019-06-11.tar.xz --alias funtoo
# ##i##lxc image import lxd-amd64-zen2-1.4-release-std-2022-04-13.tar.xz --alias funtoo
Image imported with fingerprint: fe4d27fb31bfaf3bd4f470e0ea43d26a6c05991de2a504b9e0a3b1a266dddc69
Image imported with fingerprint: fe4d27fb31bfaf3bd4f470e0ea43d26a6c05991de2a504b9e0a3b1a266dddc69
}}
}}
Line 108: Line 179:
{{console|body=
{{console|body=
# ##i##lxc image list
# ##i##lxc image list
+--------+--------------+--------+--------------------------------------------+--------+----------+------------------------------+
+--------+--------------+--------+-----------------------------------------+--------------+-----------+----------+------------------------------+
{{!}}
| ALIAS  | FINGERPRINT  | PUBLIC |              DESCRIPTION               | ARCHITECTURE |  TYPE    |   SIZE  |         UPLOAD DATE          |
ALIAS  {{!}} FINGERPRINT  {{!}} PUBLIC {{!}}                DESCRIPTION                 {{!}}  ARCH  {{!}}   SIZE  {{!}}         UPLOAD DATE          {{!}}
+--------+--------------+--------+-----------------------------------------+--------------+-----------+----------+------------------------------+
+--------+--------------+--------+--------------------------------------------+--------+----------+------------------------------+
| funtoo | b8eaa7e30c14 | no    | 1.4 Release Zen2 64bit [std] 2022-04-13 | x86_64       | CONTAINER | 342.13MB | Apr 29, 2022 at 9:36pm (UTC) |
{{!}}
+--------+--------------+--------+-----------------------------------------+--------------+-----------+----------+------------------------------+
funtoo {{!}} fe4d27fb31bf {{!}} no    {{!}} 1.3 Release Skylake 64bit [std] 2019-06-14 {{!}} x86_64 {{!}} 279.35MB {{!}} Jun 15, 2019 at 3:09am (UTC) {{!}}
+--------+--------------+--------+--------------------------------------------+--------+----------+------------------------------+
#
#
}}
}}


 
<div class="mw-translate-fuzzy">
=== Primeiro container ===
=== Primeiro container ===
</div>


Agora é hora de lançar nosso primeiro contêiner. Isso pode ser feito da seguinte forma:
Agora é hora de lançar nosso primeiro contêiner. Isso pode ser feito da seguinte forma:
Line 134: Line 204:
# ##i##lxc list
# ##i##lxc list
+---------------+---------+------+-----------------------------------------------+------------+-----------+
+---------------+---------+------+-----------------------------------------------+------------+-----------+
{{!}}
{{!}} NAME         {{!}}  STATE  {{!}} IPV4 {{!}}                    IPV6                      {{!}}    TYPE    {{!}} SNAPSHOTS {{!}}
    NAME     {{!}}  STATE  {{!}} IPV4 {{!}}                    IPV6                      {{!}}    TYPE    {{!}} SNAPSHOTS {{!}}
+---------------+---------+------+-----------------------------------------------+------------+-----------+
+---------------+---------+------+-----------------------------------------------+------------+-----------+
{{!}}
{{!}} testcontainer {{!}} RUNNING {{!}}      {{!}} fd42:8063:81cb:988c:216:3eff:fe2a:f901 (eth0) {{!}} PERSISTENT {{!}}          {{!}}
testcontainer {{!}} RUNNING {{!}}      {{!}} fd42:8063:81cb:988c:216:3eff:fe2a:f901 (eth0) {{!}} PERSISTENT {{!}}          {{!}}
+---------------+---------+------+-----------------------------------------------+------------+-----------+
+---------------+---------+------+-----------------------------------------------+------------+-----------+
#
#
}}
}}
Por padrão, nosso novo contêiner {{c |testcontainer}} usará o perfil padrão, que conectará uma interface {{c |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:
Por padrão, nosso novo contêiner {{c |testcontainer}} usará o perfil padrão, que conectará uma interface {{c |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:


Line 181: Line 248:
}}
}}


Hora de ter alguma diversão!
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 {{c|lxc list}} on your host system.
{{console|body=
%testcontainer% ##i##ego sync
}}
 


== Outro bom tutorial de administração do LXD ==
=== Network Troubleshooting ===


Esta seção contém outro bom tutorial do LXD que pode ser usado para aprender mais sobre perfis e outros recursos do LXD.
{{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
=== Terminologia ===
by running:
 
Os contêineres '' 'snapshots' '' como o nome indica, são os snapshots do contêiner no tempo, e não podem ser modificados de forma alguma. Vale a pena notar isso, porque os instantâneos podem armazenar o estado de tempo de execução do contêiner, o que nos dá a capacidade de instantâneos "com estado". Ou seja, a capacidade de reverter o contêiner, incluindo seu processador e estado de memória no momento do instantâneo.
 
LXD é baseado em '' 'imagem' '', todos os contêineres LXD vêm de uma imagem. As imagens são geralmente imagens limpas um de distribuição Linux , semelhantes às que você usaria para uma máquina virtual ou instância de nuvem. É possível "publicar" um contêiner, criando uma imagem a partir dele que pode ser usada pelos hosts LXD locais ou remotos.
 
 
=== Nossa primeira imagem ===
 
Vamos sujar as mãos ainda mais e criar nossa primeira imagem. Usaremos uma imagem genérica do Funtoo Linux de 64 bits.
 
{{note|The Funtoo's default build host is building only westmere stage for now.}}
 
Pegue a imagem aqui:
https://build.funtoo.org/funtoo-current/x86-64bit/intel64-westmere/lxd-latest.tar.xz
 
Pegue esse arquivo de hash :
https://build.funtoo.org/funtoo-current/x86-64bit/intel64-westmere/lxd-latest.tar.xz.hash.txt
 
{{tip|Check the hash of the downloaded file against the one from server. Proceed if they match. }}
 
 
==== Importe a imagem ====
 
Após o download bem-sucedido do arquivo, podemos finalmente importá-lo para o LXD e começar a usá-lo como nossa imagem "inicial" para todos os nossos contêineres.
{{console|body=
###i## lxc image import lxd-latest.tar.xz --alias funtoo
Image imported with fingerprint: 6c2ca3af0222d503656f5a1838885f1b9b6aed2c1994f1d7ef94e2efcb7233c4
###i## lxc image ls
<nowiki>+--------+--------------+--------+------------------------------------+--------+----------+-----------------------------+
| ALIAS  | FINGERPRINT  | PUBLIC |            DESCRIPTION            |  ARCH  |  SIZE  |        UPLOAD DATE        |
+--------+--------------+--------+------------------------------------+--------+----------+-----------------------------+
| funtoo | 6c2ca3af0222 | no    | Funtoo Current Generic Pure 64-bit | x86_64 |227.99MB  | Dec 13, 2017 at 11:01pm (UTC)  |
+--------+--------------+--------+------------------------------------+--------+----------+-----------------------------+
</nowiki>}}
E aí temos nossa primeira imagem do Funtoo Linux importada dentro do LXD. Você pode fazer referência à imagem pelo alias ou pela impressão digital. Apelidos podem ser adicionados também mais tarde.
 
Deixe-me mostrar-lhe alguns usos básicos então.
 
 
=== Criando seu primeiro container ===
 
Então agora podemos lançar nosso primeiro contêiner. Isso é feito usando este comando:


{{console|body=
{{console|body=
###i## lxc launch funtoo fun-1
###i## lxc network edit lxdbr0
Creating fun-1
Starting fun-1
###i##  lxc ls
<nowiki>+-------+---------+------+-----------------------------------------------+------------+-----------+
| NAME  |  STATE  | IPV4 |                    IPV6                      |    TYPE    | SNAPSHOTS |
+-------+---------+------+-----------------------------------------------+------------+-----------+
| fun-1 | RUNNING |      | fd42:156d:4593:a619:216:3eff:fef7:c1c2 (eth0) | PERSISTENT | 0        |
+-------+---------+------+-----------------------------------------------+------------+-----------+
</nowiki>}}
 
{{tip|lxc launch is a shortcut for lxc init and lxc start, lxc init creates the container without starting it. }}
 
 
==== Perfis intermezzo ====
 
O LXD tem a capacidade de alterar algumas configurações de contêiner, incluindo limitação de recursos, controle de inicialização do contêiner e uma variedade de opções de passagem de dispositivo usando o que é chamado de perfis. Vários perfis podem ser aplicados a um único contêiner e o último perfil substitui os outros, pois os recursos configurados são os mesmos para vários perfis. Deixe-me mostrar como isso pode ser usado.
 
Este é o perfil padrão que é herdado por todos os contêineres.
{{console|body=
###i## lxc profile list
<nowiki>+---------+---------+
|  NAME  | USED BY |
+---------+---------+
| default | 1      |
+---------+---------+
</nowiki>
###i##  lxc profile show default
config: {}
description: Default LXD profile
devices:
  eth0:
    nictype: bridged
    parent: lxdbr0
    type: nic
  root:
    path: /
    pool: default
    type: disk
name: default
used_by:
- /1.0/containers/fun-1
}}
}}


Agora vamos editar esse perfil para nossos contêineres funtoo. Isso incluirá algumas coisas úteis.
Then, change {{c|ipv6.nat}} YAML key value to {{c|"false"}} and restart LXD and the test container:


{{console|body=
{{console|body=
###i## lxc profile set default raw.lxc "lxc.mount.entry = none dev/shm tmpfs rw,nosuid,nodev,create=dir"
###i## /etc/init.d/lxd restart
###i## lxc profile set default environment.LANG "en_US.UTF-8"
###i## lxc restart testcontainer
###i## lxc profile set default environment.LC_ALL "en_US.UTF-8"
###i## lxc profile set default environment.LC_COLLATE "POSIX"
}}
}}


Os perfis podem armazenar qualquer configuração que um contêiner possa ter (chave/valor ou dispositivos) e qualquer número de perfis podem ser aplicados a um contêiner. Os perfis são aplicados na ordem em que são especificados, para que o último perfil a especificar uma chave específica seja vencido. Em qualquer caso, a configuração específica do recurso sempre substitui a anterior proveniente de outros perfis.
This should resolve the issue.


O perfil padrão é definido para qualquer novo contêiner criado que não especifique uma lista de perfis diferentes.
{{important|If you have initialized your LXD cluster by turning off IPv6 with the ''What IPv6 address should be used?'' option set to {{c|none}}, then the {{c|ipv6.nat}} will not even be present in our LXC local network's {{c|lxdbr0}} bridge interface.


{{note|LXD supports simple instance types. Those are represented as a string which can be passed at container creation time. [https://github.com/lxc/lxd/blob/master/doc/containers.md#instance-types containers.md#instance-types]}}
Be careful not to tamper with the {{c|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 {{c|lxdbr0}} LXC local network bridge device for reference:


=== Usando nosso primeiro container ===
{{file|name=lxc_lxdbr0.yaml|lang=YAML|desc=lxc network edit lxdbr0|body=
 
Depois de concluir todas essas personalizações, podemos começar a usar nosso contêiner.O próximo comando daremos dentro do shell do contêiner.
 
{{console|body=
###i## lxc exec fun-1 bash
}}
 
Agora você deve ver um prompt diferente começando com
 
{{console|body=
fun-1 ~ #
}}
 
Se executarmos top ou ps, por exemplo, veremos apenas os processos do contêiner.
 
{{console|body=
fun-1 ~ # ps aux
USER      PID %CPU %MEM    VSZ  RSS TTY      STAT START  TIME COMMAND
root        1  0.0  0.0  4248  748 ?        Ss+  13:20  0:00 init [3]
root      266  0.0  0.0  30488  472 ?        Ss  13:20  0:00 /usr/sbin/sshd
root      312  0.2  0.0  17996  3416 ?        Ss  13:29  0:00 bash
root      317  0.0  0.0  19200  2260 ?        R+  13:29  0:00 ps aux
}}
 
Como você pode ver, apenas os processos do contêiner são mostrados. O usuário que executa os processos é root. O que acontece se procurarmos todos os processos sshd, por exemplo, na caixa do host?
 
{{console|body=
###i## <nowiki>ps aux|grep ssh
root    14505  0.0  0.0  30564  1508 ?        Ss  Sep07  0:00 /usr/sbin/sshd 
100000  25863  0.0  0.0  30488  472 ?        Ss  15:20  0:00 /usr/sbin/sshd 
root    29487  0.0  0.0  8324  828 pts/2    S+  15:30  0:00 grep --colour=auto sshd</nowiki>
###i##
}}
 
Como você pode ver, o processo sshd está sendo executado no usuário com o uid 100000 na máquina host e possui um PID diferente.
 
 
=== Ações básicas com contêineres ===
 
 
==== Listando contêineres ====
 
{{console|body=
###i##  lxc ls
<nowiki>+-------+---------+-----------------------+------------------------------------------------+------------+-----------+
| NAME  |  STATE  |        IPV4          |                      IPV6                      |    TYPE    | SNAPSHOTS |
+-------+---------+-----------------------+------------------------------------------------+------------+-----------+
| fun-1 | RUNNING | 10.214.101.187 (eth0) | fd42:156d:4593:a619:a5ad:edaf:7270:e6c4 (eth0) | PERSISTENT | 0        |
|      |        |                      | fd42:156d:4593:a619:216:3eff:fef7:c1c2 (eth0)  |            |          |
+-------+---------+-----------------------+------------------------------------------------+------------+-----------+
</nowiki>}}
lxc ls also accepts arguments as filters. For example lxc ls web will list all containers that have web in their name.
 
 
==== Container details ====
 
{{console|body=
###i## lxc info c1
Name: c1
Remote: unix://
Architecture: x86_64
Created: 2017/09/08 02:07 UTC
Status: Running
Type: persistent
Profiles: default, prf-funtoo
Pid: 6366
Ips:
  eth0: inet    10.214.101.79  vethFG4HXG
  eth0: inet6  fd42:156d:4593:a619:8619:546e:43f:2089  vethFG4HXG
  eth0: inet6  fd42:156d:4593:a619:216:3eff:fe4a:3d4f  vethFG4HXG
  eth0: inet6  fe80::216:3eff:fe4a:3d4f        vethFG4HXG
  lo:  inet    127.0.0.1
  lo:  inet6  ::1
Resources:
  Processes: 6
  CPU usage:
    CPU usage (in seconds): 25
  Memory usage:
    Memory (current): 69.01MB
    Memory (peak): 258.92MB
  Network usage:
    eth0:
      Bytes received: 83.65kB
      Bytes sent: 9.44kB
      Packets received: 188
      Packets sent: 93
    lo:
      Bytes received: 0B
      Bytes sent: 0B
      Packets received: 0
      Packets sent: 0
}}
 
 
==== Container configuration ====
 
{{console|body=
###i##  lxc config edit c1
### This is a yaml representation of the configuration.
### Any line starting with a '# will be ignored.
###
### A sample configuration looks like:
### name: container1
### profiles:
### - default
### config:
###  volatile.eth0.hwaddr: 00:16:3e:e9:f8:7f
### devices:
###  homedir:
###    path: /extra
###    source: /home/user
###    type: disk
### ephemeral: false
###
### Note that the name is shown but cannot be changed
 
architecture: x86_64
config:
config:
   image.architecture: x86_64
   ipv4.address: 10.239.139.1/24
  image.description: Funtoo Current Generic Pure 64-bit
   ipv4.nat: "true"
  image.name: funtoo-generic_64-pure64-funtoo-current-2016-12-10
   ipv6.address: none
  image.os: funtoo
  image.release: "1.0"
  image.variant: current
  volatile.base_image: e279c16d1a801b2bd1698df95e148e0a968846835f4769b24988f2eb3700100f
  volatile.eth0.hwaddr: 00:16:3e:4a:3d:4f
  volatile.eth0.name: eth0
  volatile.idmap.base: "0"
  volatile.idmap.next: '[{"Isuid":true,"Isgid":false,"Hostid":100000,"Nsid":0,"Maprange":65536},{"Isuid":false,"Isgid":true,"Hostid":100000,"Nsid":0,"Maprange":65536}]'
   volatile.last_state.idmap: '[{"Isuid":true,"Isgid":false,"Hostid":100000,"Nsid":0,"Maprange":65536},{"Isuid":false,"Isgid":true,"Hostid":100000,"Nsid":0,"Maprange":65536}]'
   volatile.last_state.power: RUNNING
devices: {}
ephemeral: false
profiles:
- default
- prf-funtoo
stateful: false
description: ""
description: ""
name: lxdbr0
type: bridge
used_by:
- /1.0/profiles/default
- /1.0/instances/funtoo-livestream
managed: true
status: Created
locations:
- none
}}
}}


One can also add environment variables.
=== Finishing Steps ===
{{console|body=
###i## lxc config set <container> environment.LANG en_US.UTF-8
###i## lxc config set <container> environment.LC_COLLATE POSIX
}}
 
 
=== Managing files ===
 
 
=== Snapshots ===
 
 
=== Cloning, copying and moving containers ===
 
 
=== Resource control ===
 
LXD offers a variety of resource limits. Some of those are tied to the container itself, like memory quotas, CPU limits and I/O priorities. Some are tied to a particular device instead, like I/O bandwidth or disk usage limits.
 
As with all LXD configuration, resource limits can be dynamically changed while the container is running. Some may fail to apply, for example if setting a memory value smaller than the current memory usage, but LXD will try anyway and report back on failure.
 
All limits can also be inherited through profiles in which case each affected container will be constrained by that limit. That is, if you set limits.memory=256MB in the default profile, every container using the default profile (typically all of them) will have a memory limit of 256MB.
 
 
==== Disk ====
 
Setting a size limit on the container’s filesystem and have it enforced against the container. Right now LXD only supports disk limits if you’re using the ZFS or btrfs storage backend.
 
To set a disk limit (requires btrfs or ZFS):


<div class="mw-translate-fuzzy">
Hora de ter alguma diversão!
</div>
{{console|body=
{{console|body=
###i## lxc config device set c1 root size 20GB
%testcontainer% ##i##ego sync
}}
\##g##Syncing meta-repo
 
Cloning into '/var/git/meta-repo'...
 
==== CPU ====
 
To just limit a container to any 2 CPUs, do:
 
{{console|body=
###i## lxc config set c1 limits.cpu 2
}}
 
To pin to specific CPU cores, say the second and fourth:
 
{{console|body=
###i## lxc config set c1 limits.cpu 1,3
}}
 
More complex pinning ranges like this works too:
 
{{console|body=
###i## lxc config set c1 limits.cpu 0-3,7-11
}}
 
 
==== Memory ====
 
To apply a straightforward memory limit run:
 
{{console|body=
###i## lxc config set c1 limits.memory 256MB
}}
 
(The supported suffixes are kB, MB, GB, TB, PB and EB)
 
To turn swap off for the container (defaults to enabled):
 
{{console|body=
###i## lxc config set c1 limits.memory.swap false
}}
To tell the kernel to swap this container’s memory first:
 
{{console|body=
###i## lxc config set c1 limits.memory.swap.priority 0
}}
And finally if you don’t want hard memory limit enforcement:
 
{{console|body=
###i## lxc config set c1 limits.memory.enforce soft
}}
 
 
==== Network ====
 
 
==== Block I/O ====
 
 
=== Resource limits using profile - Funtoo Containers example ===
 
So I am going to create 3 profiles to mimic the resource limits for current Funtoo Containers.
 
{{TableStart}}
<tr class="danger"><th>Price</th><th>RAM</th><th>CPU Threads</th><th>Disk Space</th><th>Sign Up</th></tr>
<tr><td>'''$15/mo'''</td><td>4GB</td><td>6 CPU Threads</td><td>50GB</td><td>[https://funtoo.chargebee.com/hosted_pages/plans/container_small Sign Up! (small)]</td></tr>
<tr><td>'''$30/mo'''</td><td>12GB</td><td>12 CPU Threads</td><td>100GB</td><td>[https://funtoo.chargebee.com/hosted_pages/plans/container_medium Sign Up! (medium)]</td></tr>
<tr><td>'''$45/mo'''</td><td>48GB</td><td>24 CPU Threads</td><td>200GB</td><td>[https://funtoo.chargebee.com/hosted_pages/plans/container_large Sign Up! (large)]</td></tr>
{{TableEnd}}
 
I am going to create one profile and copy/edit it for the remaining two options.


{{console|body=
###i## lxc profile create res-small
###i## lxc profile edit res-small
config:
  limits.cpu: "6"
  limits.memory: 4GB
description: Small Variant of Funtoo Containers
devices:
  root:
    path: /
    pool: default
    size: 50GB
    type: disk
name: small
used_by: []
###i## lxc profile copy res-small res-medium
###i## lxc profile copy res-small res-large
###i## lxc profile set res-medium limits.cpu 12
###i## lxc profile set res-medium limits.memory 12GB
###i## lxc profile device set res-medium root size 100GB
###i## lxc profile set res-large limits.cpu 24
###i## lxc profile set res-large limits.memory 48GB
###i## lxc profile device set res-large root size 200GB
}}
}}
Now let's create a container and assign the res-small and funtoo profiles to it.
<div class="mw-translate-fuzzy">
{{console|body=
###i## lxc init funtoo c-small
###i## lxc profile assign c-small res-small
###i## lxc profile add c-small funtoo
}}
 
 
=== Image manipulations ===
 
 
=== Remote hosts ===
 
 
== Running systemd container on a non-systemd host ==
 
To use systemd in the container, a recent enough (>=4.6) kernel version with support for cgroup namespaces is needed. Funtoo's openrc has the fix to mount systemd cgroups, which is sufficient to run systemd based distributions lxd containers.
 
If you want to get <code>systemd</code> hierarchy mounted automatically on system startup, using <code>/etc/fstab</code> will not work, but the
{{Package|dev-libs/libcgroup}}
can be used for this. First you needed to edit the <code>/etc/cgroup/cgconfig.conf</code> and add:
{{file|name=/etc/cgroup/cgconfig.conf|body=mount {
    "name=systemd" = /sys/fs/cgroup/systemd;
}
}}
Then you need to start the cgconfig daemon:
{{console|body=
###i## rc-service cgconfig start
}}
The daemon can be started as needed, or automatically at system start by simply adding it to default group:
{{console|body=
###i## rc-update add cgconfig default
}}
 
<hr>
<hr>
 
 
== [[Special:MyLanguage/LXD/LXD in LXD|PART X - LXD in LXD]] ==
 
 
== [[Special:MyLanguage/LXD/Docker in LXD|PART Y - Docker in LXD]] ==
 
 
== [[Special:MyLanguage/LXD/FAQ|PART Z - LXD FAQ]] ==
 
 
== List of tested and working images ==
 
These are images from the https://images.linuxcontainers.org repository available by default in lxd. You can
list all available images by typing following command (beware the list is very long):
{{console|body=
###i## lxc image list images:
<nowiki>+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
|              ALIAS              | FINGERPRINT  | PUBLIC |              DESCRIPTION                |  ARCH  |  SIZE  |          UPLOAD DATE          |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.3 (3 more)            | ef69c8dc37f6 | yes    | Alpine 3.3 amd64 (20171018_17:50)        | x86_64  | 2.00MB  | Oct 18, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.3/armhf (1 more)      | 5ce4c80edcf3 | yes    | Alpine 3.3 armhf (20170103_17:50)        | armv7l  | 1.53MB  | Jan 3, 2017 at 12:00am (UTC)  |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.3/i386 (1 more)        | cd1700cb7c97 | yes    | Alpine 3.3 i386 (20171018_17:50)        | i686    | 1.84MB  | Oct 18, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.4 (3 more)            | bd4f1ccfabb5 | yes    | Alpine 3.4 amd64 (20171018_17:50)        | x86_64  | 2.04MB  | Oct 18, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.4/armhf (1 more)      | 9fe7c201924c | yes    | Alpine 3.4 armhf (20170111_20:27)        | armv7l  | 1.58MB  | Jan 11, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.4/i386 (1 more)        | 188a31315773 | yes    | Alpine 3.4 i386 (20171018_17:50)        | i686    | 1.88MB  | Oct 18, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.5 (3 more)            | 63bebc672163 | yes    | Alpine 3.5 amd64 (20171018_17:50)        | x86_64  | 1.70MB  | Oct 18, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
| alpine/3.5/i386 (1 more)        | 48045e297515 | yes    | Alpine 3.5 i386 (20171018_17:50)        | i686    | 1.73MB  | Oct 18, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
...
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
|                                | fd95a7a754a0 | yes    | Alpine 3.5 amd64 (20171016_17:50)        | x86_64  | 1.70MB  | Oct 16, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
|                                | fef66668f5a2 | yes    | Debian stretch arm64 (20171016_22:42)    | aarch64 | 96.56MB  | Oct 16, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
|                                | ff18aa2c11d7 | yes    | Opensuse 42.3 amd64 (20171017_00:53)    | x86_64  | 58.92MB  | Oct 17, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
|                                | ff4ef0d824b6 | yes    | Ubuntu zesty s390x (20171017_03:49)      | s390x  | 86.88MB  | Oct 17, 2017 at 12:00am (UTC) |
+---------------------------------+--------------+--------+------------------------------------------+---------+----------+-------------------------------+
</nowiki>}}
 
These are the images that are known to work with current LXD setup on Funtoo Linux:
{| class="wikitable sortable"
|-
! Image  !! Init !! Status
|-
| CentOS 7 || systemd || Working
|-
| Debian Jessie (8) - EOL  April/May 2020|| systemd || Working (systemd - no failed units)
|-
| Debian Stretch (9) - EOL June 2022|| systemd || Working
|-
| Fedora 26 || systemd with cgroup v2|| Not Working
|-
| Fedora 25 || systemd || Working
|-
| Fedora 24 || systemd || Working
|-
| Oracle 7 || systemd || Working (systemd - no failed units)
|-
| OpenSUSE 42.2 || systemd || Working
|-
| OpenSUSE 42.3 || systemd || Working
|-
| Ubuntu Xenial (16.04 LTS) - EOL 2021-04 || systemd || Working
|-
| Ubuntu Zesty (17.04) - EOL 2018-01 || systemd || Working
|-
| Alpine 3.3 || OpenRC || Working
|-
| Alpine 3.4 || OpenRC || Working
|-
| Alpine 3.5 || OpenRC || Working
|-
| Alpine 3.6 || OpenRC || Working
|-
| Alpine Edge || OpenRC || Working
|-
| Archlinux || systemd with cgroup v2 || Not Working
|-
| CentOS 6 || upstart || Working (systemd - no failed units)
|-
| Debian Buster || systemd with cgroup v2 || Not Working
|-
| Debian Sid || systemd with cgroup v2 || Not working
|-
| Debian Wheezy (7) - EOL May 2018 || ? || ? (more testing needed)
|-
| Gentoo || OpenRC || Working (all services started)
|-
| Oracle 6 || upstart || ? (mount outputs nothing)
|-
| Plamo 5 || ? || ?
|-
| Plamo 6 || ? || ?
|-
| Sabayon || systemd with cgroup v2 || Not Working
|-
| Ubuntu Artful (17.10) - EOL 2018-07|| systemd with cgroup v2 || Not Working
|-
| Ubuntu Core 16 || ? || ?
|-
| Ubuntu Trusty (14.04 LTS) - EOL 2019-04 || upstart || Working
|}
 
 
== Features ==
 
Some of the biggest features of LXD are:
 
* Secure by design (unprivileged containers, resource restrictions and much more)
* Scalable (from containers on your laptop to thousand of compute nodes)
* Intuitive (simple, clear API and crisp command line experience)
* Image based (no more distribution templates, only good, trusted images)
* Live migration
 
 
==== Unprivileged Containers ====
 
LXD uses unprivileged containers by default. The difference between an unprivileged container and a privileged one is whether the root user in the container is the “real” root user (uid 0 at the kernel level).
 
The way unprivileged containers are created is by taking a set of normal UIDs and GIDs from the host, usually at least 65536 of each (to be POSIX compliant) and mapping those into the container.
 
The most common example and what most LXD users will end up with by default is a map of 65536 UIDs and GIDs, with a host base id of 100000. This means that root in the container (uid 0) will be mapped to the host uid 100000 and uid 65535 in the container will be mapped to uid 165535 on the host. UID/GID 65536 and higher in the container aren’t mapped and will return an error if you attempt to use them.
 
From a security point of view, that means that anything which is not owned by the users and groups mapped into the container will be inaccessible. Any such resource will show up as being owned by uid/gid “-1” (rendered as 65534 or nobody/nogroup in userspace). It also means that should there be a way to escape the container, even root in the container would find itself with just as much privileges on the host as a nobody user.
 
LXD does offer a number of options related to unprivileged configuration:
 
* Increasing the size of the default uid/gid map
* Setting up per-container maps
* Punching holes into the map to expose host users and groups
 
 
=== Relationship with LXC ===
 
LXD isn't a rewrite of LXC, in fact it's building on top of LXC to provide a new, better user experience. Under the hood, LXD uses LXC through liblxc and its Go binding
to create and manage the containers.
 
It's basically an alternative to LXC's tools and distribution template system with the added features that come from being controllable over the network.
 
[[Category:Virtualization]]
[[Category:Virtualization]]
[[Category:Official Documentation]]
[[Category:Official Documentation]]
</div>

Revision as of 19:55, June 22, 2022

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:

   /etc/subuid
root:1000000:10000000000
   /etc/subgid
root:1000000:10000000000

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

LXD-in-LXD

The only time you will now need to set /etc/subuid and /etc/subgid now is if you are running "LXD-in-LXD". In this case, the inner LXD (within the container) will need to reduce these subuid and subgid mappings as the full range will not be available. This should be possible by simply using the following settings within your containerized LXD instance:

   /etc/subuid
root:65537:70000
   /etc/subgid
root:65537:70000

If you are not using advanced features of LXD, your LXD-in-LXD instance should now have sufficient id mappings to isolate container-containers from the host-container. The only remaining step for LXD-in-LXD would be to allow the host-container to nest:

root # lxc config set host-container security.nesting true

This will allow for host-container contain containers itself :)

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'...