Run nginx inside a docker container on systemd.
-
Decide where you want to install things.
INSTALL_DIR=/var/lib/nginx/systemd
-
Clone this repository.
$ git clone https://github.com/agross/systemd-docker-nginx.git "$INSTALL_DIR" Cloning into 'systemd-docker-nginx'...
-
Install
nginx
systemd service unit.$ "$INSTALL_DIR/install" Linking and enabling /var/lib/nginx/systemd/nginx.service Created symlink /etc/systemd/system/nginx.service → /var/lib/nginx/systemd/nginx.service. Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /var/lib/nginx/systemd/nginx.service.
-
Tell the nginx container about host-mounted paths for configuration, logs and HTML files.
systemd-docker-nginx
runs the nginx docker container with some required arguments, but you can also adddocker run
command line arguments of your own. Please seenginx.service.conf
for details.$ systemctl edit nginx.service # Editor opens. Add these lines and save the file. [Service] EnvironmentFile=/path/to/your/custom/nginx.service.conf
-
Start nginx.
$ systemctl start nginx
Depending on where your place nginx log files, you want to enable log rotatation. See NGINX_LOGS
in
your EnvironmentFile=
.
# Get the nginx log directory via EnvironmentFile=.
$ LOGS="$(systemctl show nginx.service | \
command grep --perl-regexp --only-matching 'EnvironmentFile=\K.*(?= \(ignore_errors=)' | \
xargs --no-run-if-empty grep --perl-regexp --only-matching 'NGINX_LOGS=\K.*')"
$ echo $LOGS
/var/data/nginx/log
# Create logrotate script.
$ cat <<EOF > /etc/logrotate.d/nginx
$LOGS/*.log {
daily
dateext
missingok
rotate 7
compress
delaycompress
notifempty
create
sharedscripts
postrotate
if systemctl is-active nginx.service > /dev/null 2>&1; then
# Make nginx re-open its log files.
systemctl reload nginx.service
fi
endscript
}
EOF
If you run netdata, it's recommended to start netdata after nginx such that netdata can detect nginx.
$ systemctl edit netdata.service
# Editor opens. Add these lines and save the file.
[Unit]
After=nginx.service
You can tell systemd to start another unit whenever a unit fails. See this blog post for how it is done. Also see my systemd-unit-status-mail repository that contains everything you need.
After unit-status-mail
is in place, add it to your nginx.service
using a
systemd override:
$ systemctl edit nginx.service
# Editor opens. Add these lines and save the file.
[Unit]
OnFailure=unit-status-mail@%n.service
To get all nginx.service
settings use
systemctl cat nginx.service
andsystemctl show nginx.service
.