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 -y
Verify LXC Installation:
lxc-checkconfig
Enable LXC Service:
sudo systemctl enable --now lxc
Create a New LXC Container:
sudo lxc-create -n mycontainer -t ubuntu
- Replace
mycontainer
with the name of your container. - The
-t ubuntu
flag 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/lxc
List 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 prune
Manually 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 --all
Managing LXC Containers
List Available Containers
lxc-ls --fancy
Start a Container
lxc-start -n mycontainer -d
(-d
runs it in the background)
Stop a Running Container
lxc-stop -n mycontainer
Restart a Container
lxc-restart -n mycontainer
Destroy (Delete) a Container
lxc-destroy -n mycontainer
Interacting with Containers
Attach to a Running Container
lxc-attach -n mycontainer
Run a Command Inside a Container
lxc-attach -n mycontainer -- bash
Check Container Status
lxc-info -n mycontainer
Show Container Logs
lxc-info -n mycontainer --logfile /var/log/lxc/mycontainer.log
Networking and IP Address Management
List Container IP Addresses
lxc-ls --fancy
Manually Assign an IP Address
Edit the Container’s Configuration File
nano /var/lib/lxc/<container-name>/config
Add the Following Network Configuration
lxc.net.0.ipv4.address = 192.168.1.100/24lxc.net.0.ipv4.gateway = 192.168.1.1
Replace 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 MASQUERADE
Forward a Port to a Container
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 10.0.3.20:80
Replace destination port(8080), host port(80) & internal ip(10.0.3.20)
- (This forwards traffic from
8080
on the host to port80
in the container).