server-scripts/create-php-container
2014-10-19 17:27:33 +02:00

100 lines
1.9 KiB
Bash
Executable File

#!/bin/sh
set -u
bold=`tput bold`
normal=`tput sgr0`
if ! [ $EUID -eq 0 ]
then
echo "Must be root!" >&2
exit 1
fi
if [ $# -lt 2 ]
then
echo "Usage: $0 <name> <domain> [<features>]" >&2
exit 1
fi
NAME="$1"
DOMAIN="$2"
ROOTFS="/data/containers/$NAME/rootfs"
WEBFS="/data/containers/web/rootfs"
WEBPATH="/srv/http/$DOMAIN"
NGINX="$WEBFS/etc/nginx"
PHP_MODULES=('')
shift 2
# handle extra options
while (( "$#" ))
do
case $1 in
mysql)
PHP_MODULES=(mysqli mysql pdo_mysql)
;;
postgres)
PHP_MODULES=(pgsql pdo_pgsql)
;;
esac
shift
done
# clone container
echo "${bold}Cloning container ...$normal"
TEMPFILE=$(mktemp)
ruby -rjson -e 'puts ({php_extensions: ARGV}).to_json' "$PHP_MODULES[@]" > "$TEMPFILE"
lxc-clone -o base -n "$NAME" -- --group php --vars "$TEMPFILE"
rm "$TEMPFILE"
# configure bind mount
UNIT_NAME=$(systemd-escape --path --suffix=mount "${WEBFS}${WEBPATH}")
cat << EOF > "/etc/systemd/system/$UNIT_NAME"
[Mount]
What = ${ROOTFS}${WEBPATH}
Where = ${WEBFS}${WEBPATH}
Type = none
Options = bind,ro
[Install]
WantedBy=lxc-mount.target
EOF
systemctl enable "$UNIT_NAME"
systemctl start "$UNIT_NAME"
# configure nginx
echo "${bold}Configuring nginx ...$normal"
cat << EOF > "$NGINX/sites-available/$DOMAIN"
server {
listen 80;
listen 443 ssl;
index index.php index.html index.htm;
server_name $DOMAIN;
root /srv/http/$DOMAIN;
location ~ \.(php|php5)$ {
fastcgi_pass $NAME:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}
EOF
chroot "$WEBFS" nginx_ensite "$DOMAIN"
# restart nginx
echo "${bold}Reload nginx ...$normal"
lxc-attach -n web -- systemctl reload nginx
# configure filewall
echo "${bold}Configuring firewall ...$normal"
cat << EOF > "/etc/ferm.d/services/45-$NAME"
&def_service($NAME, $NAME, tcp, 9000);
&allow_service_for($NAME, web);
EOF
fw-apply
# start container
echo "${bold}Starting container ...$normal"
lxc-start -d -n "$NAME"