Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Set up a new LXC virtual machine
# Initialize new virtual server using LXC and set up networking and HTTP proxy
# Written by: Deni Bertovic <>
# Released into Public Domain. You may use, modify and distribute it as you
# see fit.
# This script will:
# 1. Create a new LXC virtual machine based on the template container
# 2. Allocate a static IP on the LXC network (must be /24) for the new vm
# 3. Set up a SSH forwarding on a high-port (*022) from the host to the vm
# 4. Set up NGinX to forward requests for <vm>.<domain_suffix> to the new vm
# 5. Start the new VM
# To make use of this script, first prepare a virtual machine that will be
# used as the base template. Install and set up everything you'd want to
# be present on every VM.
set -e
if [[ $(/usr/bin/id -u) -ne 0 ]]; then
echo "Script needs to be run as root";
exit 1;
if [ $# -ne 1 ]; then
echo "Usage: $0 <container-name>"
exit 1;
## clone new container from minimal-template
if [ -d /var/lib/lxc/$name/ ]; then
echo "Container named $name already exists."
exit 1;
lxc-clone -o $LXC_TEMPLATE_NAME -n $name
## set up networking
macAddress=`grep "" /var/lib/lxc/$name/config | cut -d ' ' -f 2`
lastUsedIP=`tail -n 1 /etc/ethers | cut -d ' ' -f 2 | cut -d '.' -f 4`
newIP=`expr $lastUsedIP + 1`
echo "# $name" >> /etc/ethers
echo "$macAddress $LXC_NETWORK_PREFIX.$newIP" >> /etc/ethers
## restart dnsmasq to reload the new mac/ip combos from /etc/ethers
killall -s SIGHUP dnsmasq
## add ip tables rule
iptables -t nat -A PREROUTING -p tcp -d $HOST_IP -j DNAT --dport $port --to-destination $LXC_NETWORK_PREFIX.$newIP:22
iptables-save > /etc/iptables.conf
## add in autostart procedure
ln -s /var/lib/lxc/$name/config /etc/lxc/auto/$name
## start the lxc container
lxc-start -n $name -d
## set up Nginx reverse proxying
cat > /etc/nginx/sites-available/$name.$DOMAIN_SUFFIX <<EOF
server {
listen 80;
server_name $name.$DOMAIN_SUFFIX;
access_log /var/log/nginx/$name.access.log;
error_log /var/log/nginx/$name.error.log;
location / {
proxy_pass_header Server;
proxy_set_header Host \$http_host;
proxy_redirect off;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Scheme \$scheme;
proxy_connect_timeout 3;
proxy_read_timeout 10;
proxy_pass http://$LXC_NETWORK_PREFIX.$newIP:80/;
ln -s /etc/nginx/sites-available/$name.$DOMAIN_SUFFIX /etc/nginx/sites-enabled/$name.$DOMAIN_SUFFIX
nginx -t
service nginx restart
echo "New container $name created."
echo " Internal IP: $LXC_NETWORK_PREFIX.$newIP"
echo " External SSH access port: $port"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment