DevOps Lesson 7: Nginx
Nginx is the most popular web server. It serves static files, reverse proxies to Node/Python apps, handles SSL, and load balances. Essential for production.
Nginx as Reverse Proxy
# /etc/nginx/sites-available/myapp
server {
listen 80;
server_name myapp.com www.myapp.com;
# Redirect HTTP to HTTPS
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name myapp.com;
ssl_certificate /etc/letsencrypt/live/myapp.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem;
location / {
proxy_pass http://localhost:3000; # forward to Node.js
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /api/ {
proxy_pass http://localhost:4000; # different backend!
}
# Serve static files directly (faster than Node.js)
location /static/ {
root /var/www/myapp;
expires 30d;
}
}
Free SSL with Let’s Encrypt
# Install certbot
sudo apt install certbot python3-certbot-nginx
# Get free SSL certificate
sudo certbot --nginx -d myapp.com -d www.myapp.com
# Renew automatically (certbot sets up cron)
sudo certbot renew --dry-run
🏋️ Practice Task
Install Nginx locally (or in a VM/WSL). Configure it to: serve a static HTML file at /, proxy /api to a local Node.js server on port 3000, return 404 for /admin. Test with curl. Check nginx -t for config validation.
💡 Hint: sudo apt install nginx. Config in /etc/nginx/sites-available/default. sudo nginx -s reload after changes.