John Mark Causing

System Administrator | Hosting Support Engineer

Bacolod City, Philippines


John Mark Causing

System Administrator | Hosting Support Engineer

Bacolod City, Philippines


I’ve been playing around with virtual boxes and containers linux vagrant and docker. But I just discovered another tool to create another Linux container. That is called LXC! You can read more about that here if you want an introduction about LXC.

Want a better view? It looks like this

Link for the bash script source code:

Running the script.


So let’s summarize and break down the process.

Launching the linux container

We launched the container called Ubuntu 18.04 using this command:

lxc launch ubuntu:18.04 $lxcname

Generate SSH key

The script generate SSH key so you can connect to the LXC container using ssh.

ssh-keygen -f $HOME/.ssh/id_lxc_$lxcname -N '' -C 'key for local LXC'

Checking if LXC is created that has its own IPv4

The reason why I am checking this so I can transfer a file later (the public key) so we can connect via ssh

while ! [[ "${LXC_IP}" =~ ${VALID_IP} ]]; do
 # sleep 1
 #  echo "LXC ${lxcname} has still no IP "
 #  echo "Checking again.." 
 #  echo "#"
 #  echo "#"
 #  lxc list
    LXC_IP=$(lxc list | grep ${lxcname} | awk '{print $6}')
 #  echo "IP is: ${LXC_IP}"

Send the public key to LXC root authorized_key file

The reason why this is done so you have access to LXC shh as root replacing the authorized key and set the correct file permission

# Send SSH key file from this those to the target LXC
lxc file push $HOME/.ssh/id_lxc_${lxcname}.pub ${lxcname}/root/.ssh/authorized_keys --verbose

# Fixing root permission for authorized_keys file"
lxc exec ${lxcname} -- chmod 600 /root/.ssh/authorized_keys --verbose
lxc exec ${lxcname} -- chown root:root /root/.ssh/authorized_keys --verbose

Adding ssh key

This is to authorize the host to connect the LXC ssh using that authorized_key file

# Adding SSH-key for this host so we can SSH to the target LXC."
eval $(ssh-agent); 
ssh-add $HOME/.ssh/id_lxc_$lxcname

Output command to connect.

The end of the script result will give you an SSH command to connect to that LXC as root via SSH.

# Example result
ssh -i ~/.ssh/id_lxc_johnmark [email protected]

Say hello to you LXC with root access

Clean up the LXC containers.

./ clean

I hope you enjoyed this article about creating LXC linux containers automatically! Have fun!