Difference between pages "Pt-br/Funtoo Linux Kernels" and "Pt-br/Linux Containers"

(Difference between pages)
({{Package|sys-kernel/vanilla-sources}})
 
(Subsystems)
 
Line 1: Line 1:
== Overview of Kernels ==
+
== Status ==
  
=== {{Package|sys-kernel/vanilla-sources}} ===
+
Como no kernel Linux 3.1.5, o LXC é útil por isolar seus próprios trabalhos de outros. Ele não está pronto ainda para isolar potencialmente usuários de outros ou do sistema hospede (host). Para uma solução solução de containers mais madura que é apropriada para ambientes de hospedagem, veja [[OpenVZ]].
  
esse vai instalar os fontes do kernel Linux "vanilla" (não modificado). A versão atual recomendada é a 3.x. Funtoo Linux que tem suporte totalmente ao Linux 3.x. As vantagens desse kernel incluem melhoramentos recentes ao [[Pt-br/Linux_Containers|Linux Containers]], uma pilha de rede atual (networking stack) com muitas correções de bug, e alta confiabilidade para desktops e servidores. O lado negativo é que esse kernel deve ser configurado manualmente pelo usuário e não possui built-in ''<code>genkernel</code>'' suporte via a flag USE ''<code>binary</code>'' desta vez.
+
Containers LXC ainda não possui seu próprio sistema de atualização, e eles veem tudo que está na saída {{c|dmesg}} no host, enter outras coisas. Mas em geral, a tecnologia funciona.
  
=== {{Package|sys-kernel/gentoo-sources}} ===
+
== Informações Básicas ==
  
Esse kernel tree é baseado nos kernels stable do [https://www.kernel.org/ kernel.org] com genpatches aplicados [http://dev.gentoo.org/~mpagano/genpatches/about.htm genpatches].
 
o Gentoo patchset visa ter suporte à toda variedade de arquiteturas suportadas pelo Gentoo. A lista de genpatched kernels disponíveis: [http://dev.gentoo.org/~mpagano/genpatches/kernels.htm genpatches-kernels]
 
  
=== {{Package|sys-kernel/openvz-rhel6-stable}} ===
+
* Linux Containers são baseados em:
 +
** Kernel namespaces para isolamento de recurso
 +
** CGroups para limitação e contabilidade de recurso
  
Esse é um kernel baseado no RHEL6 com suporte a OpenVZ. Esse é agora o kernel preferido para desenvolvimento de produção OpenVZ (production OpenVZ deployments). Ele requer gcc-4.4.5 para ser construído, que vai usará automaticamente sem que o usuário precise utilizar ''<code>gcc-config</code>''. Utilizamos essa versão de gcc desde que essa é a versão de gcc utilizada pela Red Hat para construir esse kernel.
+
{{Package|app-emulation/lxc}} é a ferramenta userspace para os Linux containers
  
=== {{Package|sys-kernel/debian-sources}} ===
+
== Grupos de controle (Control groups) ==
  
Esse é o kernel do Debian. '''Esses ebuilds agora possuem suporte a flag USE ''<code>binary</code>''.''' Daniel adicionou comando especial <tt>config-extract</tt> que pode ser utilizado para listar todas as configurações disponíveis do kernel oficial do Debian, e gerá-las a partir dos arquivos do Debian inclusos com o kernel. Esse kernel tem suporte opcional a [[OpenVZ]], mas é bem melhor utilizar o <tt>openvz-rhel6-stable</tt> se quiser um instalação OpenVZ com qualidade de produção (production-quality OpenVZ). Para mais informações sobre como utilizar <tt>debian-sources</tt> e <tt>config-extract</tt>, veja [[#Using Debian-Sources with Genkernel|Utilizando debian-sources com o Genkernel]] abaixo.
+
* Control groups (cgroups) no kernel desde o 2.6.24
 +
** Permite agregação de tarefas e seus filhos (children)
 +
** Subsystems (cpuset, memory, blkio,...)
 +
** accounting - para medir quanto de recursos certos sistemas utilizam
 +
** resource limiting (limitante de recurso) - grupos podem ser definidos para não exceder uma definição de limite de memória
 +
** prioritization (priorização) - alguns grupos pode obter um compartilhamento maior de CPU
 +
** control - freezing/unfreezing (congelamento/descongelamento) de cgroups, checkpointing (ponto de verificação) e restarting (reinicialização)
 +
** No disk quota limitation ( -> image file, LVM, XFS, directory tree quota,...) [sem limitação de cota de disco (-> arquivo imagem, LVM, XFS, cota de arvore de diretório)]
  
== Binary USE ==
+
== Subsystems ==
 +
<br>
 +
{{console|body=
 +
###i## cat /proc/cgroups
 +
subsys_name hierarchy num_cgroups enabled
 +
cpuset
 +
cpu
 +
cpuacct
 +
memory
 +
devices
 +
freezer
 +
blkio
 +
perf_event
 +
hugetlb
 +
}}
  
Muitos dos kernel ebuilds no Funtoo Linux possuem suporte à flag USE <code>binary</code> muito útil. Ao habilitar essa flag USE e emergir o kernel, o ebuild construirá automaticamente uma imagem binária do kernel, o initramfs e módulos do kernel e instalá-los em <code>/boot</code>. A imagem binária do kernel e do initramfs pode ser utilizadas para inicializar seu sistema Funtoo Linux sem necessidade qualquer configuração adicional. Esse é um ótimo jeito de obter um sistema Funtoo Linux no ar e em execução rapidamente. Aqui está como fazer isso:
+
#cpuset    -> limita tarefas para CPU/CPUs específicos
 +
#cpu        -> compartilhamento de CPU
 +
#cpuacct    -> contabilização de CPU
 +
#memory    -> limitação de contabilização de memória e de swap
 +
#devices    -> lista de dispositivo negado ou permitido
 +
#freezer    -> suspend/resume tarefas
 +
#blkio      -> priorização I/O (weight, throttle, ...)
 +
#perf_event -> suporte para monitoramento por-cpu por-cgroup [http://lwn.net/Articles/421574/ perf_events]
 +
#hugetlb    -> recurso controlador do cgroup para páginas HugeTLB [http://lwn.net/Articles/499255/ hugetlb]
  
<console>
+
== Configuring the Funtoo Host System ==
###i## echo "sys-kernel/openvz-rhel6-stable binary" >> /etc/portage/package.use
+
###i## emerge openvz-rhel6-stable
+
###i## nano -w /etc/boot.conf
+
###i## boot-update
+
</console>
+
  
Mais informações podem ser encontradas no Guia de [[Funtoo_Linux_Installation|Instalação do Funtoo Linux]].
+
=== Install LXC kernel ===
 +
Any kernel beyond 3.1.5 will probably work. Personally I prefer {{Package|sys-kernel/gentoo-sources}} as these have support for all the namespaces without sacrificing the xfs, FUSE or NFS support for example. These checks were introduced later starting from kernel 3.5, this could also mean that the user namespace is not working optimally.
  
== Funtoo Linux Genkernel ==
+
* User namespace (EXPERIMENTAL) depends on EXPERIMENTAL and on UIDGID_CONVERTED
 +
** config UIDGID_CONVERTED
 +
*** True if all of the selected software components are known to have uid_t and gid_t converted to kuid_t and kgid_t where appropriate and are otherwise safe to use with the user namespace.
 +
**** Networking - depends on NET_9P = n
 +
**** Filesystems - 9P_FS = n, AFS_FS = n, AUTOFS4_FS = n, CEPH_FS = n, CIFS = n, CODA_FS = n, FUSE_FS = n, GFS2_FS = n, NCP_FS = n, NFSD = n, NFS_FS = n, OCFS2_FS = n, XFS_FS = n
 +
**** Security options - Grsecurity - GRKERNSEC = n (if applicable)
  
O Funtoo Linux contem uma versão forked/enhanced do genkernel com as novas compatibilidades:
+
** As of 3.10.xx kernel, all of the above options are safe to use with User namespaces, except for XFS_FS, therefore with kernel >=3.10.xx, you should answer XFS_FS = n, if you want User namespaces support.
 +
** in your kernel source directory, you should check init/Kconfig and find out what UIDGID_CONVERTED depends on
  
* genkernel pode utilizar um diretório build que é separado do diretório kernel source. Isso é habilitado utilizando a nova opção <tt>--build-dst</tt>.
+
==== Kernel configuration ====
* <code>--build-src</code> é uma nova opção que é equivalente a opção <tt>--kerneldir</tt>.
+
These options should be enable in your kernel to be able to take full advantage of LXC.
* <code>--fullname</code> pode ser utilizado para especificar o nome inteiro das imagens do kernel e do initramfs -- Tudo depois <tt>kernel-</tt> e de  <tt>initramfs-</tt>.
+
* <code>--firmware-src</code> - uma nova opção que funciona identic ao <tt>--firmware-dir</tt>.
+
* <code>--firmware-dst</code> - uma nova compatibilidade - você pode agora definir onde o genkernel instala o firmware.
+
* Genkernel utiliza o Funtoo Linux <code>lvm2</code> ao invés de construir o seu próprio.
+
* Algumas correções de compilação.
+
  
== Estabilidade do Kernel e visão geral da estabilidade ==
+
* General setup
 +
** CONFIG_NAMESPACES
 +
*** CONFIG_UTS_NS
 +
*** CONFIG_IPC_NS
 +
*** CONFIG_PID_NS
 +
*** CONFIG_NET_NS
 +
*** CONFIG_USER_NS
 +
** CONFIG_CGROUPS
 +
*** CONFIG_CGROUP_DEVICE
 +
*** CONFIG_CGROUP_SCHED
 +
*** CONFIG_CGROUP_CPUACCT
 +
*** CONFIG_CGROUP_MEM_RES_CTLR (in 3.6+ kernels it's called CONFIG_MEMCG)
 +
*** CONFIG_CGROUP_MEM_RES_CTLR_SWAP (in 3.6+ kernels it's called CONFIG_MEMCG_SWAP)
 +
*** CONFIG_CPUSETS (on multiprocessor hosts)
 +
* Networking support
 +
** Networking options
 +
*** CONFIG_VLAN_8021Q
 +
* Device Drivers
 +
** Character devices
 +
*** Unix98 PTY support
 +
**** CONFIG_DEVPTS_MULTIPLE_INSTANCES
 +
** Network device support
 +
*** Network core driver support
 +
**** CONFIG_VETH
 +
**** CONFIG_MACVLAN
  
{{Fancywarning|'''SPARC64''': Todos os kernels além das séries 3.9 e antes do 3.14-rc8 estão sujeitos a um [http://www.spinics.net/lists/sparclinux/msg11805.html bug] que abriga o kernel nas máquinas sun4v '''somente'''. Esses últimos são fornecidos com UltraSPARC T1 e mais recentes CPUs (ex. SunFire T1000, SunFire T2000, SunFire T52x0/T54x0 series...), todas as máquinas sun4u (UltraSPARC IV e CPUs antecedentes) não estão sujeitos a esse problema e qualquer versão de kernel funcional. }}
+
Once you have lxc installed, you can then check your kernel config with:
 +
{{console|body=
 +
# ##i##CONFIG=/path/to/config /usr/sbin/lxc-checkconfig
 +
}}
  
{| {{table}}
+
=== Emerge lxc ===
!Nome do Kernel
+
{{console|body=
!Versão
+
# ##i##emerge app-emulation/lxc
!USE flags
+
}}
!Estabilidade
+
!Recursos Extras
+
!Req'd udev
+
!Notas
+
|-
+
|<tt>{{Package|sys-kernel/vanilla-sources}}</tt>
+
|3.17.0
+
|N/A
+
|'''Excelente''' - recomendado para desktops e servidores.
+
|N/A
+
|Qualquer
+
|Recomendado para networking stack atuais, hardware e suporte a [[Linux Containers]]. Esse kernel deve ser manualmente configurado pelo usuário. Novos Recursos: [http://kernelnewbies.org/Linux_3.12 kernelnewbies.org/linux_3.12]  Novos Drivers: [http://kernelnewbies.org/Linux_3.12-DriversArch kernelnewbies/Linux_3.12-DriversArch]
+
|-
+
|<tt>{{Package|sys-kernel/gentoo-sources}}</tt>
+
|3.17.0
+
|N/A
+
|'''Excelente''' - recomendado para desktops e workstations
+
|N/A
+
|Qualquer
+
|Recomendado para networking stack atuais, hardware e suporte a [[Linux Containers]]. Esse kernel deve ser configurado manualmente pelo usuário. Novos Recursos: [http://kernelnewbies.org/Linux_3.12 kernelnewbies.org/linux_3.12]  Novos Drivers: [http://kernelnewbies.org/Linux_3.12-DriversArch kernelnewbies/Linux_3.12-DriversArch]
+
|-
+
|<tt>{{Package|sys-kernel/openvz-rhel6-stable}}</tt>
+
|2.6.32.042.092.2
+
|<tt>binary</tt>
+
|'''Excelente''' - recomendado para servidores de produção
+
|N/A
+
|Qualquer
+
|Esse kernel é construído com o gcc-4.4.5. <tt>emerge broadcom-netxtreme2</tt> para confiável suporte a BCM5709+ (NIC integrado)
+
  
|-
+
=== Configure Networking For Container ===
|<tt>{{Package|sys-kernel/debian-sources}}</tt>
+
|3.16.2, 3.16.7, 3.19.3
+
|<tt>openvz</tt>
+
|''Bom'' - kernel padrão recomendado pelo Funtoo
+
|OpenVZ (opcional)
+
|Qualquer
+
|Veja [[#Using debian-sources with Genkernel]], abaixo.
+
|-
+
|}
+
  
== Utilizando o Debian-Sources com o Genkernel ==
+
Typically, one uses a bridge to allow containers to connect to the network. This is how to do it under Funtoo Linux:
  
{{fancyimportant|Debian-sources está agora totalmente compatível com a flag USE ''binary'' e recomendado para usuários desktop. O exemplo abaixo é válido para instalação manual. Ao menos 12G de ''/var/tmp'' exigido para construir}}
+
# create a bridge using the Funtoo network configuration scripts. Name the bridge something like {{c|brwan}} (using {{c|/etc/init.d/netif.brwan}}). Configure your bridge to have an IP address.
 +
# Make your physical interface, such as {{c|eth0}}, an interface with no IP address (use the Funtoo {{c|interface-noip}} template.)
 +
# Make {{c|netif.eth0}} a slave of {{c|netif.brwan}} in {{c|/etc/conf.d/netif.brwan}}.
 +
# Enable your new bridged network and make sure it is functioning properly on the host.
  
Essa seção descreve como construir um kernel binário com ''<code>debian-sources</code>'' e ''<code>genkernel</code>'', e também explica como utilizar a ferramenta ''<code>config-extract</code>'' do  Funtoo Linux para listar e criar configurações do kernel oficial do Debian.
+
You will now be able to configure LXC to automatically add your container's virtual ethernet interface to the bridge when it starts, which will connect it to your network.
 +
== Setting up a Funtoo Linux LXC Container ==
  
=== Primeiro passo: emergir os pacotes necessários ===
+
Here are the steps required to get Funtoo Linux running <i>inside</i> a container. The steps below show you how to set up a container using an existing Funtoo Linux OpenVZ template. It is now also possible to use [[Metro]] to build an lxc container tarball directly, which will save you manual configuration steps and will provide an {{c|/etc/fstab.lxc}} file that you can use for your host container config. See [[Metro Recipes]] for info on how to use Metro to generate an lxc container.
  
O primeiro passo é emergir:
+
=== Create and Configure Container Filesystem ===
  
# O Debian sources
+
# Start with a Funtoo LXC template, and unpack it to a directory such as {{c|/lxc/funtoo0/rootfs/}}
# Genkernel em si
+
# Create an empty {{c|/lxc/funtoo0/fstab}} file
 +
# Ensure {{c|c1}} line is uncommented (enabled) and {{c|c2}} through {{c|c6}} lines are disabled in {{c|/lxc/funtoo0/rootfs/etc/inittab}}
  
Isso é alcançado ao executar o seguinte:
+
That's almost all you need to get the container filesystem ready to start.
  
<console>
+
=== Create Container Configuration Files ===
###i## emerge -av sys-kernel/debian-sources sys-kernel/genkernel
+
</console>
+
  
uma vez que o kernel sources do Debian são implantados, você deve encontrar um diretório nomeado '''linux-debian-''versão''''' (ex. linux-debian-2.6.32.30) sob '''<code>/usr/src</code>'''. Atualize seu link simbólico '''<code>linux</code>''' para apontar no seu diretório:
+
Create the following files:
<console>
+
###i## cd /usr/src
+
###i## rm linux
+
###i## ln -s linux-debian-2.6.32.30 linux
+
</console>
+
  
Alternativamente, emerge o debian-sources com a flag USE ''<code>symlink</code>''.
+
==== {{c|/lxc/funtoo0/config}} ====
  
=== Segundo passo: Obter um arquivo de configuração ===
 
  
É hora de baixar o arquivo de configuração do kernel. Para esse tutorial utilizaremos um arquivo de configuração para o AMD64 (várias outras arquiteturas como MIPS ou SPARC64 estão disponíveis.)  Para visualizar uma lista completa de configurações de kernel disponíveis, digite <code>./config-extract -l</code> ''' no diretório kernel source do Debian''':
+
and also create symlink from
 +
==== {{c|/lxc/funtoo0/config to /etc/lxc/funtoo0/config }} ====
 +
{{console|body=
 +
###i## install -d /etc/lxc/funtoo0
 +
###i## ln -s /lxc/funtoo0/config /etc/lxc/funtoo0/config
 +
}}
  
 +
{{note| Daniel Robbins needs to update this config to be more in line with http://wiki.progress-linux.org/software/lxc/ -- this config appears to have nice, refined device node permissions and other goodies. // note by Havis to Daniel, this config is already superior.}}
 +
 +
 +
Read "man 5 lxc.conf" , to get more information about linux container configuration file.
 
<pre>
 
<pre>
ninja1 linux-debian-2.6.32.30 # ./config-extract -l
+
## Container
 +
lxc.utsname                            = funtoo0
 +
lxc.rootfs                              = /lxc/funtoo0/rootfs/
 +
lxc.arch                                = x86_64
 +
#lxc.console                            = /var/log/lxc/funtoo0.console  # uncomment if you want to log containers console
 +
lxc.tty                                = 6 # if you plan to use container with physical terminals (eg F1..F6)
 +
#lxc.tty                                = 0  # set to 0 if you dont plan to use the container with physical terminal, also comment out in your containers /etc/inittab  c1 to c6 respawns (e.g. c1:12345:respawn:/sbin/agetty 38400 tty1 linux)
 +
lxc.pts                                = 1024
  
====== standard featureset ======
 
  
      alpha: alpha-generic, alpha-legacy, alpha-smp
+
## Capabilities
      amd64
+
lxc.cap.drop                            = audit_control
      armel: iop32x, ixp4xx, kirkwood, orion5x, versatile
+
lxc.cap.drop                            = audit_write
        hppa: parisc, parisc-smp, parisc64, parisc64-smp
+
lxc.cap.drop                            = mac_admin
        i386: 486, 686, 686-bigmem, amd64
+
lxc.cap.drop                            = mac_override
        ia64: itanium, mckinley
+
lxc.cap.drop                            = mknod
        m68k: amiga, atari, bvme6000, mac, mvme147, mvme16x
+
lxc.cap.drop                            = setfcap
        mips: 4kc-malta, 5kc-malta, r4k-ip22, r5k-ip32, sb1-bcm91250a, sb1a-bcm91480b
+
lxc.cap.drop                            = setpcap
      mipsel: 4kc-malta, 5kc-malta, r5k-cobalt, sb1-bcm91250a, sb1a-bcm91480b
+
lxc.cap.drop                            = sys_admin
    powerpc: powerpc, powerpc-smp, powerpc64
+
#lxc.cap.drop                            = sys_boot # capability to reboot the container
        s390: s390x, s390x-tape
+
#lxc.cap.drop                            = sys_chroot # required by SSH
        sh4: sh7751r, sh7785lcr
+
lxc.cap.drop                            = sys_module
      sparc: sparc64, sparc64-smp
+
#lxc.cap.drop                            = sys_nice
    sparc64: sparc64, sparc64-smp
+
lxc.cap.drop                            = sys_pacct
 +
lxc.cap.drop                            = sys_rawio
 +
lxc.cap.drop                            = sys_resource
 +
lxc.cap.drop                            = sys_time
 +
#lxc.cap.drop                            = sys_tty_config # required by getty
  
====== vserver featureset ======
+
## Devices
 +
#lxc.cgroup.devices.allow              = a # Allow access to all devices
 +
lxc.cgroup.devices.deny                = a # Deny access to all devices
  
      amd64
+
# Allow to mknod all devices (but not using them)
        i386: 686, 686-bigmem
+
lxc.cgroup.devices.allow                = c *:* m
        ia64: itanium, mckinley
+
lxc.cgroup.devices.allow                = b *:* m
    powerpc: powerpc, powerpc64
+
        s390
+
      sparc
+
    sparc64
+
  
====== xen featureset ======
+
lxc.cgroup.devices.allow                = c 1:3 rwm # /dev/null
 +
lxc.cgroup.devices.allow                = c 1:5 rwm # /dev/zero
 +
lxc.cgroup.devices.allow                = c 1:7 rwm # /dev/full
 +
lxc.cgroup.devices.allow                = c 1:8 rwm # /dev/random
 +
lxc.cgroup.devices.allow                = c 1:9 rwm # /dev/urandom
 +
#lxc.cgroup.devices.allow                = c 4:0 rwm # /dev/tty0 ttys not required if you have lxc.tty = 0
 +
#lxc.cgroup.devices.allow                = c 4:1 rwm # /dev/tty1 devices with major number 4 are "real" tty devices
 +
#lxc.cgroup.devices.allow                = c 4:2 rwm # /dev/tty2
 +
#lxc.cgroup.devices.allow                = c 4:3 rwm # /dev/tty3
 +
lxc.cgroup.devices.allow                = c 5:0 rwm # /dev/tty
 +
lxc.cgroup.devices.allow                = c 5:1 rwm # /dev/console
 +
lxc.cgroup.devices.allow                = c 5:2 rwm # /dev/ptmx
 +
lxc.cgroup.devices.allow                = c 10:229 rwm # /dev/fuse
 +
lxc.cgroup.devices.allow                = c 136:* rwm # /dev/pts/* devices with major number 136 are pts
 +
lxc.cgroup.devices.allow                = c 254:0 rwm # /dev/rtc0
  
       amd64
+
## Limits#
        i386
+
lxc.cgroup.cpu.shares                  = 1024
 +
lxc.cgroup.cpuset.cpus                = 0       # limits container to CPU0
 +
lxc.cgroup.memory.limit_in_bytes      = 512M
 +
lxc.cgroup.memory.memsw.limit_in_bytes = 1G
 +
#lxc.cgroup.blkio.weight                = 500      # requires cfq block scheduler
  
====== openvz featureset ======
+
## Filesystem
 +
#containers fstab should be outside it's rootfs dir (e.g. /lxc/funtoo0/fstab is ok, but /lxc/funtoo0/rootfs/etc/fstab is wrong!!!)
 +
#lxc.mount                              = /lxc/funtoo0/fstab     
  
      amd64
+
#lxc.mount.entry is prefered, because it supports relative paths
        i386
+
lxc.mount.entry                        = proc proc proc nosuid,nodev,noexec  0 0
</pre>
+
lxc.mount.entry                        = sysfs sys sysfs nosuid,nodev,noexec,ro 0 0
 +
lxc.mount.entry                        = devpts dev/pts devpts nosuid,noexec,mode=0620,ptmxmode=000,newinstance 0 0
 +
lxc.mount.entry                        = tmpfs dev/shm tmpfs nosuid,nodev,mode=1777 0 0
 +
lxc.mount.entry                        = tmpfs run tmpfs nosuid,nodev,noexec,mode=0755,size=128m 0 0
 +
lxc.mount.entry                        = tmpfs tmp tmpfs nosuid,nodev,noexec,mode=1777,size=1g 0 0
  
Digite <tt>config-extract -h</tt> para informações de uso extendidas:
+
##Example of having /var/tmp/portage as tmpfs in container
 +
#lxc.mount.entry                        = tmpfs var/tmp/portage tmpfs defaults,size=8g,uid=250,gid=250,mode=0775 0 0
 +
##Example of bind mount
 +
#lxc.mount.entry                        = /srv/funtoo0 /lxc/funtoo0/rootfs/srv/funtoo0 none defaults,bind 0 0
  
<pre>
+
## Network
ninja1 linux-debian-2.6.32.30 # ./config-extract -h
+
lxc.network.type                        = veth
This work is free software.
+
lxc.network.flags                      = up
 +
lxc.network.hwaddr                      = #put your MAC address here, otherwise you will get a random one
 +
lxc.network.link                        = br0
 +
lxc.network.name                        = eth0
 +
#lxc.network.veth.pair                  = veth-example
 +
</pre>
  
Copyright 2011 Funtoo Technologies. You can redistribute and/or modify it under
+
Read "man 7 capabilities" to get more information aboout Linux capabilities.
the terms of the GNU General Public License version 3 as published by the Free
+
Software Foundation. Alternatively you may (at your option) use any other
+
license that has been publicly approved for use with this program by Funtoo
+
Technologies (or its successors, if any.)
+
  
usage: config-extract [options] arch [featureset] [subarch]
+
Above, use the following command to generate a random MAC for {{c|lxc.network.hwaddr}}:
  
  -h  --help        print this usage and exit
+
{{console|body=
  -l  --list        list all available kernel configurations
+
###i## openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'
  -o  --outfile    specify kernel config outfile --
+
}}
                    defaults to .config in current directory
+
  [featureset]      defaults to "none" if not specified
+
  [subarch]        defaults to the only one available; otherwise required
+
  
This program was written by Daniel Robbins for Funtoo Linux, for the purpose of
+
It is a very good idea to assign a static MAC address to your container using {{c|lxc.network.hwaddr}}. If you don't, LXC will auto-generate a new random MAC every time your container starts, which may confuse network equipment that expects MAC addresses to remain constant.
easily and conveniently extracting Debian kernel configurations. To see a nice
+
list of all available kernel configurations, use the --list option.
+
  
Debian's kernel configs are specified internally in arch_featureset_flavor
+
It might happen from case to case that you aren't able to start your LXC Container with the above generated MAC address so for all these who run into that problem here is a little script that connects your IP for the container with the MAC address. Just save the following code as {{c|/etc/lxc/hwaddr.sh}}, make it executable and run it like {{c|/etc/lxc/hwaddr.sh xxx.xxx.xxx.xxx}} where xxx.xxx.xxx.xxx represents your Container IP. <br>{{c|/etc/lxc/hwaddr.sh}}:
format, such as: "amd64_openvz_amd64". The featureset typically describes an
+
optional kernel configuration such as "xen" or "openvz", while the flavor in
+
Debian terminology typically refers to the sub-architecture of the CPU.
+
  
When using this command, you must specify an arch. A featureset of "none" is
+
<pre>
assumed unless you specify one, and by default this program will pick the only
+
#!/bin/sh
available subarch if there is only one to choose from. If not, you will need to
+
IP=$*
pick one (and the program will remind you to do this.)
+
HA=`printf "02:00:%x:%x:%x:%x" ${IP//./ }`
 +
echo $HA
 +
</pre>
  
The kernel configuration will be written to ".config" in the current directory,
+
==== {{c|/lxc/funtoo0/fstab}} ====
or the location you specified using the -o/--outfile option.
+
{{fancynote| It is now preferable to have mount entries directly in config file instead of separate fstab:}}
 +
Edit the file {{c|/lxc/funtoo0/fstab}}:
 +
<pre>
 +
none /lxc/funtoo0/dev/pts devpts defaults 0 0
 +
none /lxc/funtoo0/proc proc defaults 0 0
 +
none /lxc/funtoo0/sys sysfs defaults 0 0
 +
none /lxc/funtoo0/dev/shm tmpfs nodev,nosuid,noexec,mode=1777,rw 0 0
 
</pre>
 
</pre>
 +
== LXC Networking ==
 +
*veth - Virtual Ethernet (bridge)
 +
*vlan - vlan interface (requires device able to do vlan tagging)
 +
*macvlan (mac-address based virtual lan tagging) has 3 modes:
 +
**private
 +
**vepa (Virtual Ethernet Port Aggregator)
 +
**bridge
 +
*phys - dedicated host NIC
 +
[https://blog.flameeyes.eu/2010/09/linux-containers-and-networking Linux Containers and Networking]
  
Vamos utilizar <tt>config-extract</tt> para gerar uma configuração de kernel para um sistema amd64:
+
Enable routing on the host:
 +
By default Linux workstations and servers have IPv4 forwarding disabled.
 +
{{console|body=
 +
###i## echo "1" > /proc/sys/net/ipv4/ip_forward
 +
###i## cat /proc/sys/net/ipv4/ip_forward
 +
# 1
 +
}}
 +
== Initializing and Starting the Container ==
  
<console>
+
You will probably need to set the root password for the container before you can log in. You can use chroot to do this quickly:
# ##i##cd linux
+
# ##i##./config-extract amd64
+
Wrote amd64_none_amd64 kernel configuration to /usr/src/linux-debian-2.6.32.30/.config.
+
</console>
+
  
<tt>config-extract</tt> também lhe permite extrair configurações de recursos especiais do Debian, tal como configurações de kernels para Xen e [[OpenVZ]]:
+
{{console|body=
 +
###i## chroot /lxc/funtoo0/rootfs
 +
(chroot) ###i## passwd
 +
New password: XXXXXXXX
 +
Retype new password: XXXXXXXX
 +
passwd: password updated successfully
 +
(chroot) ###i## exit
 +
}}
  
<console>
+
Now that the root password is set, run:
# ##i##./config-extract amd64 openvz
+
Wrote amd64_openvz_amd64 kernel configuration to /usr/src/linux-debian-2.6.32.30/.config.
+
</console>
+
  
'''É necessário nomear o nome do arquivo de configuração do kernel para outro diferente de ".config" para evitar erros com o genkernel.'''
+
{{console|body=
 +
###i## lxc-start -n funtoo0 -d
 +
}}
  
 +
The {{c|-d}} option will cause it to run in the background.
  
Depois de utilizar o <tt>config-extract</tt>, execute <tt>make oldconfig</tt> e aceite todas as opções padrões ao pressionar Enter em todos os prompts.
+
To attach to the console:
  
 +
{{console|body=
 +
###i## lxc-console -n funtoo0
 +
}}
  
{{fancynote|se vocẽ estiver utilizando o sistema de arquivo XFS como sua partição root: execute <tt>make menuconfig</tt> e certifiqui-se de que "File Systems --> XFS filesystem support" e "Library Routines --> CRC32c (Castagnoli, et al) Cyclic Redundancy-Check" estão ambos configurados para * (e não [m]).}}
+
You should now be able to log in and use the container. In addition, the container should now be accessible on the network.
Isso é necessário para assegurar que seu sistema pode inicializar corretamente pelas versẽos do kernel >= 3.10.11.
+
  
=== Terceiro passo: Construir e instalar o kernel ===
+
To directly attach to container:
  
Isso é simplesmente obtido ao:
+
{{console|body=
 +
###i## lxc-attach -n funtoo0
 +
}}
  
<console>
+
To stop the container:
# ##i##genkernel --kernel-config=config-2.6.32-5-amd64 all
+
</console>
+
  
* --kernel-config: utilize o configfile dado. Se você der somente um filename aqui, ele é procurando em seu diretório de funcionamento atual. Você pode também utilizar um caminho relativo ou absoluto (relative or an absolute path) guiando o seu configfile aqui (por exemplo: "--kernel-config=/usr/src/linux/configfile").
+
{{console|body=
* all: reconstrua a imagem do kernel e a imagem da ramdisk initramfs (aparte dos módulos do kernel, a imagem do ramdisk contem as ferramentas como BusyBox e alguns scripts de genéricos inicialização, dependendo das opções que você utilizar na linha de comando várias ferramentas adicionais como lvm ou raid volume management podem ser incorporados também).
+
###i## lxc-stop -n funtoo0
 +
}}
  
{{ fancyimportant|Ao menos que seja explicitamente declarado via ''--no-clean'' ou ''--no-mrproper'', o Genkernel fará um '''make mrproper''' no kernel source tree, limpando assim o build anterior '''e removendo o aqruivo de configuração de kernel anterior''' nisso.  
+
Ensure that networking is working from within the container while it is running, and you're good to go!
 +
== Starting LXC container during host boot ==
 +
 
 +
# You need to create symlink in {{c|/etc/init.d/}} to {{c|/etc/init.d/lxc}} so that it reflects your container.
 +
# {{c|ln -s /etc/init.d/lxc /etc/init.d/lxc.funtoo0}}
 +
# now you can add {{c|lxc.funtoo0}} to default runlevel
 +
# {{c|rc-update add lxc.funtoo0 default}}
 +
{{console|body=
 +
###i## rc
 +
* Starting funtoo0 ...                 [ ok ]
 
}}
 
}}
 +
== LXC Bugs/Missing Features ==
 +
 +
This section is devoted to documenting issues with the current implementation of LXC and its associated tools. We will be gradually expanding this section with detailed descriptions of problems, their status, and proposed solutions.
 +
 +
=== reboot ===
 +
 +
* By default, lxc does not support rebooting a container from within. It will simply stop and the host will not know to start it.
 +
* If you want your container to reboot gracefully, you need sys_boot capability (comment out lxc.cap.drop = sys_boot in your container config)
 +
 +
=== PID namespaces ===
 +
 +
Process ID namespaces are functional, but the container can still see the CPU utilization of the host via the system load (ie. in {{c|top}}).
 +
 +
=== /dev/pts newinstance ===
 +
 +
* Some changes may be required to the host to properly implement "newinstance" {{c|/dev/pts}}. See [https://bugzilla.redhat.com/show_bug.cgi?id=501718 This Red Hat bug].
 +
 +
=== lxc-create and lxc-destroy ===
 +
 +
* LXC's shell scripts are badly designed and are sure way to destruction, avoid using lxc-create and lxc-destroy.
 +
 +
=== network initialization and cleanup ===
 +
 +
* If used network.type = phys after lxc-stop the interface will be renamed to value from lxc.network.link. It supposed to be fixed in 0.7.4, happens still on 0.7.5 - http://www.mail-archive.com/lxc-users@lists.sourceforge.net/msg01760.html
 +
 +
* Re-starting a container can result in a failure as network resource are tied up from the already-defunct instance: [http://www.mail-archive.com/lxc-devel@lists.sourceforge.net/msg00824.html]
 +
 +
=== graceful shutdown ===
 +
 +
* To gracefully shutdown a container, it's init system needs to properly handle kill -PWR signal
 +
* For funtoo/gentoo make sure that you have:
 +
** pf:12345:powerwait:/sbin/halt
 +
** in your containers /etc/inittab
 +
* For debian/ubuntu make sure that you have:
 +
** pf::powerwait:/sbin/shutdown -t1 -a -h now
 +
** in your container /etc/inittab
 +
** and also comment out other line starting with pf:powerfail (such as pf::powerwait:/etc/init.d/powerfail start) <- these are used if you have UPS monitoring daemon installed!
 +
* /etc/init.d/lxc seems to have broken support for graceful shutdown (it sends proper signal, but then also tries to kill the init with lxc-stop)
 +
 +
=== funtoo ===
 +
 +
* Our udev should be updated to contain {{c|-lxc}} in scripts. (This has been done as of 02-Nov-2011, so should be resolved. But not fixed in our openvz templates, so need to regen them in a few days.)
 +
* Our openrc should be patched to handle the case where it cannot mount tmpfs, and gracefully handle this situation somehow. (Work-around in our docs above, which is to mount tmpfs to {{c|/libexec/rc/init.d}} using the container-specific {{c|fstab}} file (on the host.)
 +
* Emerging udev within a container can/will fail when realdev is run, if a device node cannot be created (such as /dev/console) if there are no mknod capabilities within the container. This should be fixed.
 +
== References ==
 +
 +
* {{c|man 7 capabilities}}
 +
* {{c|man 5 lxc.conf}}
 +
== Links ==
 +
 +
* There are a number of additional lxc features that can be enabled via patches: [http://lxc.sourceforge.net/patches/linux/3.0.0/3.0.0-lxc1/]
 +
* [https://wiki.ubuntu.com/UserNamespace Ubuntu User Namespaces page]
 +
* lxc-gentoo setup script [https://github.com/globalcitizen/lxc-gentoo on GitHub]
  
Se você utiliza o Genkernel para reconstruir o kernel Linux em SPARC64, lembre-se de:
+
* '''IBM developerWorks'''
* Definir '''sparc64-unknown-linux-gnu-''' no ''General setup --> Cross-compiler tool prefix''
+
** [http://www.ibm.com/developerworks/linux/library/l-lxc-containers/index.html LXC: Linux Container Tools]
* Colocar '''--kernel-cross-compile=sparc64-unknown-linux-gnu-''' na linha de comando Genkernel
+
** [http://www.ibm.com/developerworks/linux/library/l-lxc-security/ Secure Linux Containers Cookbook]
  
Uma vez que o kernel tem sido compilado a ram disk (ramdisk) tem sido gerada, a imagem do kernel mais seus arquivos associados (imagem initramfs e System.map) são colocados no diretório /boot. Você pode utilizar sua ferramenta favorita para atualizar seus arquivos de configuração de bootloader.
+
* '''Linux Weekly News'''
 +
** [http://lwn.net/Articles/244531/ Smack for simplified access control]
  
[[Category:Internals]]
+
[[Category:Labs]]
[[Category:Funtoo features]]
+
[[Category:HOWTO]]
[[Category:Kernel]]
+
[[Category:Virtualization]]
[[Category:Official Documentation]]
+

Revision as of 21:43, April 12, 2015

Status

Como no kernel Linux 3.1.5, o LXC é útil por isolar seus próprios trabalhos de outros. Ele não está pronto ainda para isolar potencialmente usuários de outros ou do sistema hospede (host). Para uma solução solução de containers mais madura que é apropriada para ambientes de hospedagem, veja OpenVZ.

Containers LXC ainda não possui seu próprio sistema de atualização, e eles veem tudo que está na saída dmesg no host, enter outras coisas. Mas em geral, a tecnologia funciona.

Informações Básicas

  • Linux Containers são baseados em:
    • Kernel namespaces para isolamento de recurso
    • CGroups para limitação e contabilidade de recurso

Package:LXC é a ferramenta userspace para os Linux containers

Grupos de controle (Control groups)

  • Control groups (cgroups) no kernel desde o 2.6.24
    • Permite agregação de tarefas e seus filhos (children)
    • Subsystems (cpuset, memory, blkio,...)
    • accounting - para medir quanto de recursos certos sistemas utilizam
    • resource limiting (limitante de recurso) - grupos podem ser definidos para não exceder uma definição de limite de memória
    • prioritization (priorização) - alguns grupos pode obter um compartilhamento maior de CPU
    • control - freezing/unfreezing (congelamento/descongelamento) de cgroups, checkpointing (ponto de verificação) e restarting (reinicialização)
    • No disk quota limitation ( -> image file, LVM, XFS, directory tree quota,...) [sem limitação de cota de disco (-> arquivo imagem, LVM, XFS, cota de arvore de diretório)]

Subsystems


# cat /proc/cgroups 
subsys_name	hierarchy	num_cgroups	enabled
cpuset	
cpu	
cpuacct	
memory	
devices	
freezer	
blkio	
perf_event
hugetlb


  1. cpuset -> limita tarefas para CPU/CPUs específicos
  2. cpu -> compartilhamento de CPU
  3. cpuacct -> contabilização de CPU
  4. memory -> limitação de contabilização de memória e de swap
  5. devices -> lista de dispositivo negado ou permitido
  6. freezer -> suspend/resume tarefas
  7. blkio -> priorização I/O (weight, throttle, ...)
  8. perf_event -> suporte para monitoramento por-cpu por-cgroup perf_events
  9. hugetlb -> recurso controlador do cgroup para páginas HugeTLB hugetlb

Configuring the Funtoo Host System

Install LXC kernel

Any kernel beyond 3.1.5 will probably work. Personally I prefer No results as these have support for all the namespaces without sacrificing the xfs, FUSE or NFS support for example. These checks were introduced later starting from kernel 3.5, this could also mean that the user namespace is not working optimally.

  • User namespace (EXPERIMENTAL) depends on EXPERIMENTAL and on UIDGID_CONVERTED
    • config UIDGID_CONVERTED
      • True if all of the selected software components are known to have uid_t and gid_t converted to kuid_t and kgid_t where appropriate and are otherwise safe to use with the user namespace.
        • Networking - depends on NET_9P = n
        • Filesystems - 9P_FS = n, AFS_FS = n, AUTOFS4_FS = n, CEPH_FS = n, CIFS = n, CODA_FS = n, FUSE_FS = n, GFS2_FS = n, NCP_FS = n, NFSD = n, NFS_FS = n, OCFS2_FS = n, XFS_FS = n
        • Security options - Grsecurity - GRKERNSEC = n (if applicable)
    • As of 3.10.xx kernel, all of the above options are safe to use with User namespaces, except for XFS_FS, therefore with kernel >=3.10.xx, you should answer XFS_FS = n, if you want User namespaces support.
    • in your kernel source directory, you should check init/Kconfig and find out what UIDGID_CONVERTED depends on

Kernel configuration

These options should be enable in your kernel to be able to take full advantage of LXC.

  • General setup
    • CONFIG_NAMESPACES
      • CONFIG_UTS_NS
      • CONFIG_IPC_NS
      • CONFIG_PID_NS
      • CONFIG_NET_NS
      • CONFIG_USER_NS
    • CONFIG_CGROUPS
      • CONFIG_CGROUP_DEVICE
      • CONFIG_CGROUP_SCHED
      • CONFIG_CGROUP_CPUACCT
      • CONFIG_CGROUP_MEM_RES_CTLR (in 3.6+ kernels it's called CONFIG_MEMCG)
      • CONFIG_CGROUP_MEM_RES_CTLR_SWAP (in 3.6+ kernels it's called CONFIG_MEMCG_SWAP)
      • CONFIG_CPUSETS (on multiprocessor hosts)
  • Networking support
    • Networking options
      • CONFIG_VLAN_8021Q
  • Device Drivers
    • Character devices
      • Unix98 PTY support
        • CONFIG_DEVPTS_MULTIPLE_INSTANCES
    • Network device support
      • Network core driver support
        • CONFIG_VETH
        • CONFIG_MACVLAN

Once you have lxc installed, you can then check your kernel config with:

# CONFIG=/path/to/config /usr/sbin/lxc-checkconfig


Emerge lxc

# emerge app-emulation/lxc


Configure Networking For Container

Typically, one uses a bridge to allow containers to connect to the network. This is how to do it under Funtoo Linux:

  1. create a bridge using the Funtoo network configuration scripts. Name the bridge something like brwan (using /etc/init.d/netif.brwan). Configure your bridge to have an IP address.
  2. Make your physical interface, such as eth0, an interface with no IP address (use the Funtoo interface-noip template.)
  3. Make netif.eth0 a slave of netif.brwan in /etc/conf.d/netif.brwan.
  4. Enable your new bridged network and make sure it is functioning properly on the host.

You will now be able to configure LXC to automatically add your container's virtual ethernet interface to the bridge when it starts, which will connect it to your network.

Setting up a Funtoo Linux LXC Container

Here are the steps required to get Funtoo Linux running inside a container. The steps below show you how to set up a container using an existing Funtoo Linux OpenVZ template. It is now also possible to use Metro to build an lxc container tarball directly, which will save you manual configuration steps and will provide an /etc/fstab.lxc file that you can use for your host container config. See Metro Recipes for info on how to use Metro to generate an lxc container.

Create and Configure Container Filesystem

  1. Start with a Funtoo LXC template, and unpack it to a directory such as /lxc/funtoo0/rootfs/
  2. Create an empty /lxc/funtoo0/fstab file
  3. Ensure c1 line is uncommented (enabled) and c2 through c6 lines are disabled in /lxc/funtoo0/rootfs/etc/inittab

That's almost all you need to get the container filesystem ready to start.

Create Container Configuration Files

Create the following files:

/lxc/funtoo0/config

and also create symlink from

/lxc/funtoo0/config to /etc/lxc/funtoo0/config

# install -d /etc/lxc/funtoo0
# ln -s /lxc/funtoo0/config /etc/lxc/funtoo0/config


Note
Daniel Robbins needs to update this config to be more in line with http://wiki.progress-linux.org/software/lxc/ -- this config appears to have nice, refined device node permissions and other goodies. // note by Havis to Daniel, this config is already superior.


Read "man 5 lxc.conf" , to get more information about linux container configuration file.

## Container
lxc.utsname                             = funtoo0
lxc.rootfs                              = /lxc/funtoo0/rootfs/
lxc.arch                                = x86_64
#lxc.console                            = /var/log/lxc/funtoo0.console  # uncomment if you want to log containers console
lxc.tty                                 = 6  # if you plan to use container with physical terminals (eg F1..F6)
#lxc.tty                                = 0  # set to 0 if you dont plan to use the container with physical terminal, also comment out in your containers /etc/inittab  c1 to c6 respawns (e.g. c1:12345:respawn:/sbin/agetty 38400 tty1 linux)
lxc.pts                                 = 1024


## Capabilities
lxc.cap.drop                            = audit_control
lxc.cap.drop                            = audit_write
lxc.cap.drop                            = mac_admin
lxc.cap.drop                            = mac_override
lxc.cap.drop                            = mknod
lxc.cap.drop                            = setfcap
lxc.cap.drop                            = setpcap
lxc.cap.drop                            = sys_admin
#lxc.cap.drop                            = sys_boot # capability to reboot the container
#lxc.cap.drop                            = sys_chroot # required by SSH
lxc.cap.drop                            = sys_module
#lxc.cap.drop                            = sys_nice
lxc.cap.drop                            = sys_pacct
lxc.cap.drop                            = sys_rawio
lxc.cap.drop                            = sys_resource
lxc.cap.drop                            = sys_time
#lxc.cap.drop                            = sys_tty_config # required by getty

## Devices
#lxc.cgroup.devices.allow               = a # Allow access to all devices
lxc.cgroup.devices.deny                 = a # Deny access to all devices

# Allow to mknod all devices (but not using them)
lxc.cgroup.devices.allow                = c *:* m
lxc.cgroup.devices.allow                = b *:* m

lxc.cgroup.devices.allow                = c 1:3 rwm # /dev/null
lxc.cgroup.devices.allow                = c 1:5 rwm # /dev/zero
lxc.cgroup.devices.allow                = c 1:7 rwm # /dev/full
lxc.cgroup.devices.allow                = c 1:8 rwm # /dev/random
lxc.cgroup.devices.allow                = c 1:9 rwm # /dev/urandom
#lxc.cgroup.devices.allow                = c 4:0 rwm # /dev/tty0 ttys not required if you have lxc.tty = 0
#lxc.cgroup.devices.allow                = c 4:1 rwm # /dev/tty1 devices with major number 4 are "real" tty devices
#lxc.cgroup.devices.allow                = c 4:2 rwm # /dev/tty2
#lxc.cgroup.devices.allow                = c 4:3 rwm # /dev/tty3
lxc.cgroup.devices.allow                = c 5:0 rwm # /dev/tty
lxc.cgroup.devices.allow                = c 5:1 rwm # /dev/console
lxc.cgroup.devices.allow                = c 5:2 rwm # /dev/ptmx
lxc.cgroup.devices.allow                = c 10:229 rwm # /dev/fuse
lxc.cgroup.devices.allow                = c 136:* rwm # /dev/pts/* devices with major number 136 are pts
lxc.cgroup.devices.allow                = c 254:0 rwm # /dev/rtc0

## Limits#
lxc.cgroup.cpu.shares                  = 1024
lxc.cgroup.cpuset.cpus                 = 0        # limits container to CPU0
lxc.cgroup.memory.limit_in_bytes       = 512M
lxc.cgroup.memory.memsw.limit_in_bytes = 1G
#lxc.cgroup.blkio.weight                = 500      # requires cfq block scheduler

## Filesystem
#containers fstab should be outside it's rootfs dir (e.g. /lxc/funtoo0/fstab is ok, but /lxc/funtoo0/rootfs/etc/fstab is wrong!!!)
#lxc.mount                               = /lxc/funtoo0/fstab       

#lxc.mount.entry is prefered, because it supports relative paths
lxc.mount.entry                         = proc proc proc nosuid,nodev,noexec  0 0
lxc.mount.entry                         = sysfs sys sysfs nosuid,nodev,noexec,ro 0 0
lxc.mount.entry                         = devpts dev/pts devpts nosuid,noexec,mode=0620,ptmxmode=000,newinstance 0 0
lxc.mount.entry                         = tmpfs dev/shm tmpfs nosuid,nodev,mode=1777 0 0
lxc.mount.entry                         = tmpfs run tmpfs nosuid,nodev,noexec,mode=0755,size=128m 0 0
lxc.mount.entry                         = tmpfs tmp tmpfs nosuid,nodev,noexec,mode=1777,size=1g 0 0

##Example of having /var/tmp/portage as tmpfs in container 
#lxc.mount.entry                         = tmpfs var/tmp/portage tmpfs defaults,size=8g,uid=250,gid=250,mode=0775 0 0
##Example of bind mount
#lxc.mount.entry                        = /srv/funtoo0 /lxc/funtoo0/rootfs/srv/funtoo0 none defaults,bind 0 0

## Network
lxc.network.type                        = veth
lxc.network.flags                       = up
lxc.network.hwaddr                      = #put your MAC address here, otherwise you will get a random one
lxc.network.link                        = br0
lxc.network.name                        = eth0
#lxc.network.veth.pair                   = veth-example

Read "man 7 capabilities" to get more information aboout Linux capabilities.

Above, use the following command to generate a random MAC for lxc.network.hwaddr:

# openssl rand -hex 6


It is a very good idea to assign a static MAC address to your container using lxc.network.hwaddr. If you don't, LXC will auto-generate a new random MAC every time your container starts, which may confuse network equipment that expects MAC addresses to remain constant.

It might happen from case to case that you aren't able to start your LXC Container with the above generated MAC address so for all these who run into that problem here is a little script that connects your IP for the container with the MAC address. Just save the following code as /etc/lxc/hwaddr.sh, make it executable and run it like /etc/lxc/hwaddr.sh xxx.xxx.xxx.xxx where xxx.xxx.xxx.xxx represents your Container IP.
/etc/lxc/hwaddr.sh:

#!/bin/sh
IP=$*
HA=`printf "02:00:%x:%x:%x:%x" ${IP//./ }`
echo $HA

/lxc/funtoo0/fstab

Note
It is now preferable to have mount entries directly in config file instead of separate fstab:

Edit the file /lxc/funtoo0/fstab:

none /lxc/funtoo0/dev/pts devpts defaults 0 0
none /lxc/funtoo0/proc proc defaults 0 0
none /lxc/funtoo0/sys sysfs defaults 0 0
none /lxc/funtoo0/dev/shm tmpfs nodev,nosuid,noexec,mode=1777,rw 0 0

LXC Networking

  • veth - Virtual Ethernet (bridge)
  • vlan - vlan interface (requires device able to do vlan tagging)
  • macvlan (mac-address based virtual lan tagging) has 3 modes:
    • private
    • vepa (Virtual Ethernet Port Aggregator)
    • bridge
  • phys - dedicated host NIC

Linux Containers and Networking

Enable routing on the host: By default Linux workstations and servers have IPv4 forwarding disabled.

# echo "1" > /proc/sys/net/ipv4/ip_forward
# cat /proc/sys/net/ipv4/ip_forward
# 1

Initializing and Starting the Container

You will probably need to set the root password for the container before you can log in. You can use chroot to do this quickly:

# chroot /lxc/funtoo0/rootfs
(chroot) # passwd
New password: XXXXXXXX
Retype new password: XXXXXXXX
passwd: password updated successfully
(chroot) # exit


Now that the root password is set, run:

# lxc-start -n funtoo0 -d


The -d option will cause it to run in the background.

To attach to the console:

# lxc-console -n funtoo0


You should now be able to log in and use the container. In addition, the container should now be accessible on the network.

To directly attach to container:

# lxc-attach -n funtoo0


To stop the container:

# lxc-stop -n funtoo0


Ensure that networking is working from within the container while it is running, and you're good to go!

Starting LXC container during host boot

  1. You need to create symlink in /etc/init.d/ to /etc/init.d/lxc so that it reflects your container.
  2. ln -s /etc/init.d/lxc /etc/init.d/lxc.funtoo0
  3. now you can add lxc.funtoo0 to default runlevel
  4. rc-update add lxc.funtoo0 default
# rc
 * Starting funtoo0 ...                  [ ok ]

LXC Bugs/Missing Features

This section is devoted to documenting issues with the current implementation of LXC and its associated tools. We will be gradually expanding this section with detailed descriptions of problems, their status, and proposed solutions.

reboot

  • By default, lxc does not support rebooting a container from within. It will simply stop and the host will not know to start it.
  • If you want your container to reboot gracefully, you need sys_boot capability (comment out lxc.cap.drop = sys_boot in your container config)

PID namespaces

Process ID namespaces are functional, but the container can still see the CPU utilization of the host via the system load (ie. in top).

/dev/pts newinstance

  • Some changes may be required to the host to properly implement "newinstance" /dev/pts. See This Red Hat bug.

lxc-create and lxc-destroy

  • LXC's shell scripts are badly designed and are sure way to destruction, avoid using lxc-create and lxc-destroy.

network initialization and cleanup

  • Re-starting a container can result in a failure as network resource are tied up from the already-defunct instance: [1]

graceful shutdown

  • To gracefully shutdown a container, it's init system needs to properly handle kill -PWR signal
  • For funtoo/gentoo make sure that you have:
    • pf:12345:powerwait:/sbin/halt
    • in your containers /etc/inittab
  • For debian/ubuntu make sure that you have:
    • pf::powerwait:/sbin/shutdown -t1 -a -h now
    • in your container /etc/inittab
    • and also comment out other line starting with pf:powerfail (such as pf::powerwait:/etc/init.d/powerfail start) <- these are used if you have UPS monitoring daemon installed!
  • /etc/init.d/lxc seems to have broken support for graceful shutdown (it sends proper signal, but then also tries to kill the init with lxc-stop)

funtoo

  • Our udev should be updated to contain -lxc in scripts. (This has been done as of 02-Nov-2011, so should be resolved. But not fixed in our openvz templates, so need to regen them in a few days.)
  • Our openrc should be patched to handle the case where it cannot mount tmpfs, and gracefully handle this situation somehow. (Work-around in our docs above, which is to mount tmpfs to /libexec/rc/init.d using the container-specific fstab file (on the host.)
  • Emerging udev within a container can/will fail when realdev is run, if a device node cannot be created (such as /dev/console) if there are no mknod capabilities within the container. This should be fixed.

References

  • man 7 capabilities
  • man 5 lxc.conf

Links