Step-by-Step Guide to Installing and Optimizing NGINX on Amazon Linux 2 for Production Environments
Most guides stop at basic installation. This post not only walks you through setting up NGINX on Amazon Linux 2 but also dives into essential optimizations and security best practices that seasoned engineers swear by to avoid common pitfalls in production environments.
Why NGINX on Amazon Linux 2?
NGINX is a high-performance web server and reverse proxy widely used in cloud architectures. When running on Amazon Linux 2—the stable, secure, and AWS-optimized Linux distribution—it offers a robust platform for scalable web applications. Proper installation and tuning ensure your infrastructure is reliable, efficient, and secure.
Prerequisites
- An Amazon EC2 instance running Amazon Linux 2
- Basic knowledge of SSH and Linux command line
- Non-root user with sudo privileges
Step 1: Connect to Your Amazon Linux 2 EC2 Instance
Use SSH to connect:
ssh -i your-key.pem ec2-user@your-ec2-public-ip
Replace your-key.pem
with your private key file, and your-ec2-public-ip
with your instance’s public IP address.
Step 2: Update System Packages
Start by ensuring all system packages are up to date:
sudo yum update -y
This secures your system from known vulnerabilities.
Step 3: Install NGINX
Amazon Linux 2 comes with the amazon-linux-extras
repository which includes NGINX versions.
To list available topics:
sudo amazon-linux-extras list | grep nginx
Enable the NGINX module (for example, version 1.12):
sudo amazon-linux-extras enable nginx1
sudo yum clean metadata
Now install NGINX:
sudo yum install nginx -y
Verify installation:
nginx -v
You should see something like:
nginx version: nginx/1.12.2
Step 4: Start and Enable NGINX Service
Start the NGINX service:
sudo systemctl start nginx
Ensure it starts on boot:
sudo systemctl enable nginx
Check status:
sudo systemctl status nginx
Step 5: Adjust Firewall Rules (If Applicable)
If you use AWS Security Groups, open port 80 for HTTP and port 443 for HTTPS.
Example ingress rules in AWS Console or CLI:
Protocol | Port Range | Source |
---|---|---|
TCP | 80 | 0.0.0.0/0 |
TCP | 443 | 0.0.0.0/0 |
If using firewalld
or iptables
locally (generally not required on EC2), allow traffic accordingly.
Step 6: Verify Default NGINX Page
In your web browser, navigate to your EC2 instance’s public IP (e.g., http://your-ec2-public-ip).
You should see the default Welcome to nginx! page.
Step 7: Configure Basic NGINX Server Block (Virtual Host)
It’s best practice to create separate server blocks for your applications instead of modifying the default config.
Create a new configuration file:
sudo vi /etc/nginx/conf.d/example.com.conf
Add this sample configuration replacing example.com
with your domain or public IP:
server {
listen 80;
server_name example.com www.example.com;
root /usr/share/nginx/html/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}
Create the root directory and add a test page:
sudo mkdir -p /usr/share/nginx/html/example.com
echo "<h1>Welcome to example.com!</h1>" | sudo tee /usr/share/nginx/html/example.com/index.html
Test configuration syntax:
sudo nginx -t
If OK, reload NGINX:
sudo systemctl reload nginx
Visit http://example.com (or your server IP) to verify.
Step 8: Optimize NGINX for Production
Worker Processes & Connections
Edit /etc/nginx/nginx.conf
to optimize performance.
Open file:
sudo vi /etc/nginx/nginx.conf
Modify these directives inside the events {}
and main sections as follows (adjust based on CPU cores):
worker_processes auto;
worker_connections 1024;
multi_accept on;
use epoll; # Available on Linux – boosts event handling efficiency
events {
worker_connections 1024;
multi_accept on;
}
Explanation:
worker_processes auto;
allows NGINX to automatically match worker count to CPU cores.worker_connections
controls max simultaneous connections per worker.multi_accept on;
allows accepting multiple new connections at once.- Using the
epoll
model enhances I/O scalability on Linux servers like Amazon Linux.
Reload config after changes:
sudo nginx -s reload
# or
sudo systemctl reload nginx
Enable Gzip Compression
Compress responses to reduce bandwidth utilization — important for production.
Add this inside http {}
block in /etc/nginx/nginx.conf
or in a separate config under /etc/nginx/conf.d/
:
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_buffers 16 8k;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 256;
Reload NGINX afterwards.
Set Proper Timeouts
Add timeouts inside the http {}
block or respective server block to prevent hung connections eating resources.
Example settings inside /etc/nginx/nginx.conf
HTTP block or location/server block:
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 65s;
send_timeout 10s;
Step 9: Secure Your Installation
Disable Server Tokens
Prevent sending version info in HTTP headers by adding below inside the main context (http {}
block) or server blocks if needed:
server_tokens off;
This reduces risk of automated attacks targeting known vulnerabilities.
Configure SELinux/AppArmor (Optional)
Amazon Linux uses SELinux — ensure it’s permissive or configured correctly if enabled.
Check status with:
sestatus
For most setups, keep SELinux in permissive mode unless you have strict compliance.
Step 10: Set Up HTTPS (Recommended for Production)
Use Let’s Encrypt free SSL certificates via Certbot tool.
Install Certbot & Dependencies
First install EPEL repo for Certbot packages:
sudo amazon-linux-extras install epel -y
sudo yum install certbot python3-certbot-nginx -y
Obtain SSL Certificate:
Run Certbot with NGINX plugin auto-configure HTTPS redirect:
sudo certbot --nginx
Follow prompts to enter email, agree TOS, select domain names configured in NGINX server blocks.
Certbot will automatically obtain certificates and edit your configs to serve HTTPS securely with automatic renewal cron jobs installed.
Test HTTPS access now via https://example.com/
Bonus Tips for Production Stability & Monitoring
- Log rotation: Confirm logs under
/var/log/nginx/
rotate properly vialogrotate
- Monitoring: Use CloudWatch agent or other monitoring tools tailored for EC2/Nginx metrics.
- Auto-restart: Make sure failures restart service automatically (
systemctl enable --now nginx
) - Load testing: Before launching production workloads, simulate load with tools like ApacheBench (
ab
) or wrk. - Backup configs: Keep backups of customized configurations in source control or off-instance storage.
Conclusion
Installing NGINX on Amazon Linux 2 is straightforward thanks to Amazon's optimized repositories—but configuring it correctly for production requires attention to performance tuning security best practices like disabling tokens, enabling gzip compression, tuning worker processes/timeouts, and securing traffic via TLS encryption.
With these steps applied, you'll have a rock-solid foundation powering scalable web apps efficiently and securely within AWS ecosystems!
Happy hosting! 🚀