Skip to content

Instantly share code, notes, and snippets.

@Natureshadow
Last active September 9, 2015 12:17
Show Gist options
  • Save Natureshadow/3d87574025b9649d70de to your computer and use it in GitHub Desktop.
Save Natureshadow/3d87574025b9649d70de to your computer and use it in GitHub Desktop.
Quick and dirty hack for microservice port assignment and Apache proxy registration
# This systemd unit can be used to start a Java (Springboot) microservice, and…
# … have it use a context-path depending on the active unit name,
# … have it use a unique port depending on the unit name (a numeric hash),
# … have it register a HTTP proxy pass with Apache.
#
# For the numeric hashing part, this unit depends on the MirBSD Korn Shell (mksh)
# being available.
#
# Copyright © 2015 Dominik George <nik@naturalnet.de>
# Contributions and corrections by Mirko Hoffmann <m.hoffmann@tarent.de>
# Created for tarent solutions GmbH
#
# Licensed under the MIT License.
[Unit]
Description=%p instance for %i
[Service]
Type=simple
User=%p
Group=%p
PermissionsStartOnly=true
WorkingDirectory=/opt/%p
ExecStart=/bin/mksh -c '/usr/bin/java -Xms1G -Xmx1G -Dspring.profiles.active=%i -jar %p.jar --server.context-path=/%i --server.port=$$(</run/%p/%i.port)'
ExecStartPre=/bin/mksh -c 'mkdir -p /run/%p; u=%n; typeset -i h=0x$${u@#}; p=$$((# (h & 1023) + 62000 )); echo $$p >/run/%p/%i.port'
ExecStartPost=/bin/mksh -c 'p=$$(</run/%p/%i.port); cd /etc/apache2/conf-available; /bin/echo -e "ProxyPass /%i http://localhost:$$p/%i\nProxyPassReverse /%i http://localhost:$$p/%i" >%p-%i.conf; /usr/sbin/a2enconf %p-%i; /usr/sbin/apache2ctl restart'
ExecStopPost=/bin/mksh -c '/usr/sbin/a2disconf %p-%i; rm -f /etc/apache2/conf-available/%p-%i.conf; /usr/sbin/apache2ctl restart; rm -rf /run/%p'
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment