Install LXC Container on Linux System
Updated:
Installing LXC:
- Ubuntu/Debian System
sudo apt updatesudo apt install lxc lxc-utils lxc-templates -y- Centos System
sudo yum install epel-release -ysudo yum install lxc lxc-utils lxc-templates -yVerify LXC Installation:
lxc-checkconfigEnable LXC Service:
sudo systemctl enable --now lxcCreate a New LXC Container:
sudo lxc-create -n mycontainer -t ubuntu- Replace
mycontainerwith the name of your container. - The
-t ubuntuflag specifies an Ubuntu template.
If you get an error about missing images,
Update the template cache:
sudo lxc-create -t download -n mycontainer -- -d ubuntu -r focal -a amd64-d ubuntu: Distribution likecentos,debian,busybox-r focal: Ubuntu version (change to your preferred version)-a amd64: Architecture
Managing LXC Images
List Available LXC Images on Local:
- images stored locally
lxc image list local:- if using traditional LXC
ls /var/lib/lxcList Remote Images from the LXC Repository:
lxc image list images:Show detailed information about an image
lxc image info <image-alias-or-fingerprint>Replace the image name/fingerprint, example: abcd1234
Remove an LXC Image
lxc image delete <image-alias-or-fingerprint>Remove All Unused Images
lxc image pruneManually Delete an Image (If Needed)
rm -rf /var/lib/lxd/<image-name>or
rm -rf /var/lib/lxd/images/<image-name>- Refresh LXC Images:
lxc image refresh --allManaging LXC Containers
List Available Containers
lxc-ls --fancyStart a Container
lxc-start -n mycontainer -d(-d runs it in the background)
Stop a Running Container
lxc-stop -n mycontainerRestart a Container
lxc-restart -n mycontainerDestroy (Delete) a Container
lxc-destroy -n mycontainerInteracting with Containers
Attach to a Running Container
lxc-attach -n mycontainerRun a Command Inside a Container
lxc-attach -n mycontainer -- bashCheck Container Status
lxc-info -n mycontainerShow Container Logs
lxc-info -n mycontainer --logfile /var/log/lxc/mycontainer.logNetworking and IP Address Management
List Container IP Addresses
lxc-ls --fancyManually Assign an IP Address
Edit the Container’s Configuration File
nano /var/lib/lxc/<container-name>/configAdd the Following Network Configuration
lxc.net.0.ipv4.address = 192.168.1.100/24lxc.net.0.ipv4.gateway = 192.168.1.1Replace ip(192.168.1.100) & gateway(192.168.1.1)
Enable NAT (Network Address Translation)
sudo apt install iptables; \sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADEForward a Port to a Container
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 10.0.3.20:80Replace destination port(8080), host port(80) & internal ip(10.0.3.20)
- (This forwards traffic from
8080on the host to port80in the container).