Diferencia entre revisiones de «LXD»

De Jose Castillo Aliaga
Ir a la navegación Ir a la búsqueda
Línea 337: Línea 337:
ephemeral: false
ephemeral: false
</pre>
</pre>
També es pot executar
$ lxc config edit xamp
I afegir el nic. D'aquesta manera és més sencill i evitar errades en el comandament. No obstant el comandament anterior permet executar-lo en un script.
'''En molts contenidors'''
Es pot crear i editar un perfil:
$ lxc profile create bridged
$ lxc profile device add bridged eth0 nic nictype=bridged parent=br0
$ lxc launch ubuntu:16.04 test --profile=bridged
o afegir a contenidors existents:
$ lxc profile apply xamp default,bridged


=== Accedir de l'exterior ===
=== Accedir de l'exterior ===

Revisión del 21:41 23 oct 2016

Instal·lació

 sudo apt-get install lxd
 newgrp lxd


En ubuntu, els usuaris han de formar part del grup LXD per poder utilitzar-lo.

Observem que passa si fem lxc sense paràmetres:

$ lxc
Usage: lxc [subcommand] [options]
Órdenes disponibles
	config     - Manage configuration.
	copy       - Copy containers within or in between lxd instances.
	delete     - Delete containers or container snapshots.
	exec       - Execute the specified command in a container.
	file       - Manage files on a container.
	help       - Presents details on how to use LXD.
	image      - Manipulate container images.
	info       - List information on LXD servers and containers.
	launch     - Launch a container from a particular image.
	list       - Lists the available resources.
	move       - Move containers within or in between lxd instances.
	profile    - Manage configuration profiles.
	publish    - Publish containers as images.
	remote     - Manage remote LXD servers.
	restart    - Changes state of one or more containers to restart.
	restore    - Set the current state of a resource back to a snapshot.
	snapshot   - Create a read-only snapshot of a container.
	start      - Changes state of one or more containers to start.
	stop       - Changes state of one or more containers to stop.
	version    - Prints the version number of this client tool.

Opciones:
  --all              Print less common commands.
  --debug            Print debug information.
  --verbose          Print verbose information.

Entorno:
  LXD_CONF           Path to an alternate client configuration directory.
  LXD_DIR            Path to an alternate server directory.

Ens interessa fer una configuració prèvia per a crear els contenidors correctament:

$ sudo lxd init
Name of the storage backend to use (dir or zfs): dir
Would you like LXD to be available over the network (yes/no)? yes
Address to bind LXD to (not including port): 10.0.2.15
Port to bind LXD to (8443 recommended): 
Invalid input, try again.

Port to bind LXD to (8443 recommended): 8443
Trust password for new clients: 
Again: 
Do you want to configure the LXD bridge (yes/no)? yes
Warning: Stopping lxd.service, but it can still be activated by:
  lxd.socket
LXD has been successfully configured.

Observa que demana coses molt concretes que seran distintes en cada cas.

Si creem contenidors, aquest asistent deixa de funcionar i apareix açò:

sudo lxd init
LXD init cannot be used at this time.
However if all you want to do is reconfigure the network,
you can still do so by running "sudo dpkg-reconfigure -p medium lxd"

error: You have existing containers or images. lxd init requires an empty LXD.

Podem executar el comandament que ens recomana per a reconfigurar la xarxa.

Contenidors i imatges

Si fem:

$ lxc image list
Generating a client certificate. This may take a minute...
If this is your first time using LXD, you should also run: sudo lxd init
To start your first container, try: lxc launch ubuntu:16.04

+-------+-------------+--------+--------------+-----+---------+-------------+
| ALIAS | FINGERPRINT | PUBLIC | DESCRIPCIÓN | ARQ | TAMAÑO | UPLOAD DATE |
+-------+-------------+--------+--------------+-----+---------+-------------+

Encara no tenim descarregada ninguna imatge, però ens dona l'opció de configurar en lxd init i de llançar un contenidor en lxc launch ubuntu:16.04.

jose@server:~$ lxc launch ubuntu:16.04
Creando sandless-yair
Retrieving image: 100%
Iniciando sandless-yair
jose@server:~$ lxc list
+---------------+---------+------+------+------------+-----------+
|    NOMBRE     | ESTADO  | IPV4 | IPV6 |    TIPO    | SNAPSHOTS |
+---------------+---------+------+------+------------+-----------+
| sandless-yair | RUNNING |      |      | PERSISTENT | 0         |
+---------------+---------+------+------+------------+-----------+
jose@server:~$ lxc image list
+-------+--------------+--------+---------------------------------------------+--------+----------+------------------------------+
| ALIAS | FINGERPRINT  | PUBLIC |                DESCRIPCIÓN                 |  ARQ   | TAMAÑO  |         UPLOAD DATE          |
+-------+--------------+--------+---------------------------------------------+--------+----------+------------------------------+
|       | de051f59f701 | no     | ubuntu 16.04 LTS amd64 (release) (20161011) | x86_64 | 143.12MB | Oct 14, 2016 at 9:43am (UTC) |
+-------+--------------+--------+---------------------------------------------+--------+----------+------------------------------+

Mirem cóm ha descarregat la imatge, ha creat el contenidor i la imatge està disponible ja en el sistema.

Backend

LXD pot anar directament al sistema d'arxius en /var/lib/lxd. No obstant, és més interessant utilitzar ZFS per els avantatges que proporciona.

En principi, instal·lant ZFS ja es pot utilitzar i permet crear volumens mentres es fa el lxd init.

Ús dels contenidors

  • Llistar contenidors
lxc list # Llista dels contenidors instal·lats
lxc image list ubuntu: # Llista de les imatges d'ubuntu disponibles
lxc image alias list ubuntu:
lxc list --fast
lxc list --fast ubuntu
  • Crear un contenidor sense llançar-lo:
lxc init ubuntu:
  • Llançar un contenidor nou lxc launch <imagen> [nombre]
  • Obtindre informació del contenidor: lxc info <container>
$ lxc info u1
Nombre: u1
Arquitectura: x86_64
Creación: 2016/10/19 16:17 UTC
Estado: Running
Type: persistent
Perfiles: default
PID: 20968
Ips:
  eth0:	inet	10.243.177.208	vethB8LY7C
  eth0:	inet6	fe80::216:3eff:fe35:d02b	vethB8LY7C
  lo:	inet	127.0.0.1
  lo:	inet6	::1
Resources:
  Procesos: 25
  Disk usage:
    root: 7.14MB
  Memory usage:
    Memory (current): 48.40MB
    Memory (peak): 169.30MB
  Network usage:
    eth0:
      Bytes received: 1.53kB
      Bytes sent: 1.34kB
      Packets received: 15
      Packets sent: 11
    lo:
      Bytes received: 248 bytes
      Bytes sent: 248 bytes
      Packets received: 4
      Packets sent: 4
  • Detindre un contenidor lxc stop <nombre>
  • Encendre un contenidor lxc start <nombre>
  • Pausar un contenidor: lxc pause <container>
  • Obtindre un shell en un contenidor lxc exec <nombre> -- /bin/bash

Aquest shell no és exactament com connectar-se per SSH, ja que els comandaments no s'executen dins dels contenidor. Per tant, no coneix configuracions del shell o variables d'entorn. Sempre s'executen con al root del contenidor (que no és el mateix que el de la màquina).

lxc exec <container> bash
# Alguns necessiten un separador
lxc exec <container> -- ls -lh /
  • Esborrar un contenidor o snapshot lxc delete <nombre>

Configuracions

Els contenidors es poden configurar de múltiples maneres possibles. Es poden crear perfils per a configurar varis contenidors amb profiles:

lxc profile list
lxc profile show <profile>
lxc profile edit <profile>
lxc profile apply <container> <profile1>,<profile2>,<profile3>,...

Si volem configurar un sol contenidor no té sentit fer un profile. Cal cridar a:

lxc config edit <container>
lxc config set <container> <key> <value>
lxc config device add my-container kvm unix-char path=/dev/kvm
lxc config show <container>
lxc config show --expanded <container>

En qualsevol cas, si no sabem cóm utilitzar config, es pot executar:

lxc help config
lxc help profile
Aquestes configuracions es poden aplicar sense tindre que parar els contenidors

Exemples

Fer que un contenidor arranque a l'inici:

$ lxc config set container_name boot.autostart 1

Snapshots

Crear el Snapshot:

lxc snapshot <container>
lxc snapshot <container> <snapshot name>

Llistar els snapshots d'un contenidor:

lxc info <container>

Restaurar un snapshot:

lxc restore <container> <snapshot name>

Renombrar un snapshot:

lxc move <container>/<snapshot name> <container>/<new snapshot name>

Crear un contenidor a partir d'un snapshot. Sols canvia la MAC:

lxc copy <container> / <snapshot name> <destination container>

Esborrar un snapshot:

lxc delete <container>/<snapshot name>

Moure contenidors

Clonar un contenidor:

lxc copy <container> <destination container>

Reanomenar el contenidor:

lxc move <old name> <new name>

Copiar fitxers

Per a extraure un fitxer d'un contenidor:

lxc file pull <container>/<path> <dest>

Mostrar un fitxer per eixida estàndar:

lxc file pull zerotier/etc/hosts -

Copiar un fitxer dins:

lxc file push <origen> <container>/<path>

Editar dirèctament un fitxer:

lxc file edit <container>/<path>

El problema és que no actualitza el fitxer fins que no tanques l'editor. Per tant, es pot fer un push en una altra terminal del fitxer creat en /tmp. Exemple:

lxc file push lxd_file_edit_718115826 xamp/var/www/html/tema6/scripts/script.js


# off-topic: Canviar el editor per defecte
sudo update-alternatives --install /usr/bin/editor editor /usr/bin/gedit 10
sudo update-alternatives --config editor

Crear i gestionar imatges i tarballs

Usuaris

https://help.ubuntu.com/lts/serverguide/lxd.html#lxd-uid

Quotes

Gestionar discos

Xarxa

Quant creem un contenidor, la seua configuració de xarxa està especificada en /etc/default/lxd-bridge.

Observem el que passa al fer ifconfig:

jose@server:~$ ifconfig 
enp0s3    Link encap:Ethernet  direcciónHW 08:00:27:e8:3b:93  
          Direc. inet:10.0.2.15  Difus.:10.0.2.255  Másc:255.255.255.0
          Dirección inet6: fe80::a00:27ff:fee8:3b93/64 Alcance:Enlace
          ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST  MTU:1500  Métrica:1
          Paquetes RX:211835 errores:0 perdidos:0 overruns:0 frame:0
          Paquetes TX:105051 errores:0 perdidos:0 overruns:0 carrier:0
          colisiones:0 long.colaTX:1000 
          Bytes RX:165676776 (165.6 MB)  TX bytes:6341150 (6.3 MB)

lo        Link encap:Bucle local  
          Direc. inet:127.0.0.1  Másc:255.0.0.0
          Dirección inet6: ::1/128 Alcance:Anfitrión
          ACTIVO BUCLE FUNCIONANDO  MTU:65536  Métrica:1
          Paquetes RX:160 errores:0 perdidos:0 overruns:0 frame:0
          Paquetes TX:160 errores:0 perdidos:0 overruns:0 carrier:0
          colisiones:0 long.colaTX:1 
          Bytes RX:11840 (11.8 KB)  TX bytes:11840 (11.8 KB)

lxdbr0    Link encap:Ethernet  direcciónHW fe:ef:19:c3:53:10  
          Dirección inet6: fe80::7875:78ff:fe2e:d0f5/64 Alcance:Enlace
          Dirección inet6: fe80::1/64 Alcance:Enlace
          ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST  MTU:1500  Métrica:1
          Paquetes RX:8 errores:0 perdidos:0 overruns:0 frame:0
          Paquetes TX:5 errores:0 perdidos:0 overruns:0 carrier:0
          colisiones:0 long.colaTX:1000 
          Bytes RX:536 (536.0 B)  TX bytes:470 (470.0 B)

vethGNE6GU Link encap:Ethernet  direcciónHW fe:ef:19:c3:53:10  
          Dirección inet6: fe80::fcef:19ff:fec3:5310/64 Alcance:Enlace
          ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST  MTU:1500  Métrica:1
          Paquetes RX:8 errores:0 perdidos:0 overruns:0 frame:0
          Paquetes TX:8 errores:0 perdidos:0 overruns:0 carrier:0
          colisiones:0 long.colaTX:1000 
          Bytes RX:648 (648.0 B)  TX bytes:648 (648.0 B)

A banda de la targeta real (enp0s3) i la de loopback, trobem un pont anomenat lxdbr0 i una targeta amb un nom extrany. El pont el proporciona lxd i funciona com a NAT cap a l'exterior. La targeta extranya ès la eth0 de dins del contenidor i està visible al fer ifconfig perquè els contenidors comparteixen el Kernel amb el sistema operatiu.

Al instal·lar LXD, per defecte crea el pont lxdbr0 que sols proporciona connectivitat IPv6 amb el host. Per activar la IPv4 i la possiblitat de connectar a Internet, cal executar el lxd init abans de tot o el dpkg-reconfigure -p medium lxd

LXD proporciona varies maneres de configurar la xarxa.

Per defecte ens dona una xarxa tipus bridged que funciona correctament per a la majoria dels casos. La xarxa bridged es connecta al pont lxdbr0 i aquest fa un NAT amb l'exterior. Poden haver problemes amb els DNS i, sobretot, per connectar de l'exterior al contenidor.

Anem a veure els tipus de xarxa que es poden configurar:

LXD supports different kind of network devices:
- physical: Straight physical device passthrough from the host. The targeted device will vanish from the host and appear in the container.
- bridged: Uses an existing bridge on the host and creates a virtual device pair to connect the host bridge to the container.
- macvlan: Sets up a new network device based on an existing one but using a different MAC address.
- p2p: Creates a virtual device pair, putting one side in the container and leaving the other side on the host.

Crear un nou nic

En un sol contenidor

$ lxc config device add xamp eth1 nic nictype=bridged parent=lxdbr0
Device eth1 added to xamp
$ lxc config show --expanded xamp
name: xamp
profiles:
- default
config:
  volatile.base_image: 6f25adef061c3f2186c6910bff8cacd0c63e1493e3f8b616e52eb84076890bd1
  volatile.eth0.hwaddr: 00:16:3e:11:3d:0a
  volatile.eth1.hwaddr: 00:16:3e:05:3e:90
  volatile.eth1.name: eth1
  volatile.last_state.idmap: '[{"Isuid":true,"Isgid":false,"Hostid":296608,"Nsid":0,"Maprange":65536},{"Isuid":false,"Isgid":true,"Hostid":296608,"Nsid":0,"Maprange":65536}]'
devices:
  eth0:
    name: eth0
    nictype: bridged
    parent: lxdbr0
    type: nic
  eth1:
    nictype: bridged
    parent: lxdbr0
    type: nic
  root:
    path: /
    type: disk
ephemeral: false

També es pot executar

$ lxc config edit xamp

I afegir el nic. D'aquesta manera és més sencill i evitar errades en el comandament. No obstant el comandament anterior permet executar-lo en un script.

En molts contenidors

Es pot crear i editar un perfil:

$ lxc profile create bridged
$ lxc profile device add bridged eth0 nic nictype=bridged parent=br0
$ lxc launch ubuntu:16.04 test --profile=bridged

o afegir a contenidors existents:

$ lxc profile apply xamp default,bridged

Accedir de l'exterior

En xarxa Bridged

Amb IPtables

Imaginem que tenim un servidor web que escolta al port 80:

En el servidor que continga LXD:

# iptables -t nat -A PREROUTING -i enp0s3 -p tcp --dport 80 -j DNAT --to 10.243.177.135:80
# iptables -t nat -A PREROUTING -i enp0s3 -p tcp --dport 443 -j DNAT --to 10.243.177.135:443
# iptables-save >  /etc/iptables/rules.v4

En cas de que el servidor estiga en una màquina virtual en Virtualbox:

Reenviamentportsvirtualbox.png

Ara podem accedir amb el navegador web amb: localhost:8080

Amb ponts

Un altra manera és creant un nou pont:

auto br0
iface br0 inet manual
bridge-ports eth1
$ dpkg-reconfigure lxd

En xarxa physical

En principi funcionarà dirèctament, ja que deixa al host sense targeta i la clava dins del contenidor. No és recomanable, ja que pots deixar el servidor sense xarxa. Sols en cas d'us servici molt intensiu en un servidor en varies targetes dedicades.

En xarxa macvlan

També pot funcionar directament.

$ lxc profile device set default eth0 nictype macvlan
$ lxc profile device set default eth0 parent eth1

Enllaços