Deploy Systemd Service Behind Nginx with TLS
Published on
Table of Contents
🔗Systemd Service
sudo tee /etc/systemd/system/YOUR_SERVICE_NAME.service << 'EOF'
[Unit]
Description=YOUR_SERVICE_NAME
After=network.target
[Service]
ExecStart=/executable/location
WorkingDirectory=/dir/where/program/can/read-write/data
Restart=on-failure
RestartSec=5s
StartLimitIntervalSec=300
StartLimitBurst=5
User=ubuntu
Group=ubuntu
[Install]
WantedBy=multi-user.target
EOF
Start command:
sudo systemctl daemon-reload
sudo systemctl enable YOUR_SERVICE_NAME
sudo systemctl start YOUR_SERVICE_NAME
Other commands:
# see logs
sudo journalctl -u YOUR_SERVICE_NAME -f
# restart
sudo systemctl restart YOUR_SERVICE_NAME
# when service file is updated
sudo systemctl daemon-reload
🔗Nginx Reverse Proxy
sudo tee /etc/nginx/sites-available/YOUR_DOMAIN << 'EOF'
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream server_list {
server localhost:8000;
keepalive 32;
}
server {
listen 80; # IPv4
listen [::]:80; # IPv6
server_name YOUR_DOMAIN;
# Hide server information headers
server_tokens off;
# Enable gzip compression
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_min_length 1024;
gzip_types
application/atom+xml
application/geo+json
application/javascript
application/x-javascript
application/json
application/ld+json
application/manifest+json
application/rdf+xml
application/rss+xml
application/xhtml+xml
application/xml
font/eot
font/otf
font/ttf
image/svg+xml
text/css
text/javascript
text/plain
text/xml;
# Buffer size optimization
client_body_buffer_size 32k;
client_header_buffer_size 2k;
client_max_body_size 10M;
large_client_header_buffers 4 2k;
# Timeouts
client_body_timeout 20;
client_header_timeout 20;
keepalive_timeout 65;
send_timeout 20;
# Proxy settings
location / {
include proxy_params;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_redirect off;
proxy_buffering on;
proxy_buffer_size 16k;
proxy_buffers 8 16k;
proxy_pass http://server_list;
# Additional proxy timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 120s;
proxy_read_timeout 120s;
}
# Security headers
add_header X-Content-Type-Options "nosniff" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
}
EOF
Create Symlink
sudo ln -s /etc/nginx/sites-available/YOUR_DOMAIN /etc/nginx/sites-enabled/
Checks Nginx configuration
sudo nginx -t
Restart Nginx
sudo systemctl restart nginx
🔗Letsencrypt SSL
Installing certbot
to install TLS certificate
sudo apt remove certbot
sudo snap install core; sudo snap refresh core
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
sudo certbot --nginx -d YOUR_DOMAIN