Align Nginx config, proxy script, and service unit with EC2 internalsInstance
This commit is contained in:
parent
0fdfc34e83
commit
0a06bce9fe
3 changed files with 75 additions and 69 deletions
|
|
@ -1,64 +1,38 @@
|
||||||
import os
|
import os
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import sys
|
import sys
|
||||||
|
import subprocess
|
||||||
|
|
||||||
CONF_SRC = "/tmp/crmbackend.nginx.conf"
|
def main():
|
||||||
DEST_CONF_D = "/etc/nginx/conf.d/crmbackend.conf"
|
source_conf = '/tmp/crmbackend.nginx.conf'
|
||||||
DEST_SNIPPET = "/etc/nginx/snippets/crmbackend.conf"
|
target_available = '/etc/nginx/sites-available/crmbackend'
|
||||||
SITES_AVAILABLE = "/etc/nginx/sites-available"
|
target_enabled = '/etc/nginx/sites-enabled/crmbackend'
|
||||||
SITES_ENABLED = "/etc/nginx/sites-enabled"
|
|
||||||
|
|
||||||
def run_cmd(cmd):
|
if not os.path.exists(source_conf):
|
||||||
print(f"Running: {' '.join(cmd)}")
|
source_conf = '/home/ubuntu/crmbackend/crmbackend.nginx.conf'
|
||||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
|
||||||
if res.returncode != 0:
|
|
||||||
print(f"Error ({res.returncode}): {res.stderr}")
|
|
||||||
else:
|
|
||||||
print(res.stdout)
|
|
||||||
return res.returncode == 0
|
|
||||||
|
|
||||||
def configure_nginx():
|
if not os.path.exists(source_conf):
|
||||||
if not os.path.exists(CONF_SRC):
|
print(f"Error: Nginx configuration source file not found at {source_conf}")
|
||||||
print(f"Warning: {CONF_SRC} not found!")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# Ensure conf.d directory exists
|
try:
|
||||||
os.makedirs("/etc/nginx/conf.d", exist_ok=True)
|
# Copy to sites-available
|
||||||
shutil.copy2(CONF_SRC, DEST_CONF_D)
|
subprocess.run(['sudo', 'cp', source_conf, target_available], check=True)
|
||||||
print(f"Copied {CONF_SRC} to {DEST_CONF_D}")
|
print(f"Copied {source_conf} to {target_available}")
|
||||||
|
|
||||||
# Check nginx syntax
|
# Enable site symlink
|
||||||
if run_cmd(["sudo", "nginx", "-t"]):
|
if not os.path.exists(target_enabled):
|
||||||
run_cmd(["sudo", "systemctl", "reload", "nginx"])
|
subprocess.run(['sudo', 'ln', '-sf', target_available, target_enabled], check=True)
|
||||||
print("Nginx reloaded successfully.")
|
print(f"Symlinked {target_available} to {target_enabled}")
|
||||||
else:
|
|
||||||
# If placing in conf.d failed (e.g., location directive outside server block),
|
|
||||||
# place in snippets and try to include in the active site block if needed.
|
|
||||||
os.makedirs("/etc/nginx/snippets", exist_ok=True)
|
|
||||||
shutil.copy2(CONF_SRC, DEST_SNIPPET)
|
|
||||||
os.remove(DEST_CONF_D)
|
|
||||||
print(f"Moved configuration to snippet: {DEST_SNIPPET}")
|
|
||||||
|
|
||||||
# Try to include snippet in default site or active sites
|
# Test Nginx configuration
|
||||||
default_site = os.path.join(SITES_AVAILABLE, "default")
|
test_res = subprocess.run(['sudo', 'nginx', '-t'], capture_output=True, text=True)
|
||||||
if os.path.exists(default_site):
|
if test_res.returncode == 0:
|
||||||
with open(default_site, "r") as f:
|
subprocess.run(['sudo', 'systemctl', 'reload', 'nginx'], check=True)
|
||||||
content = f.read()
|
print("Nginx configuration verified and reloaded successfully.")
|
||||||
if "crmbackend.conf" not in content:
|
|
||||||
# Insert include before the last closing brace
|
|
||||||
idx = content.rfind("}")
|
|
||||||
if idx != -1:
|
|
||||||
new_content = content[:idx] + f"\n include {DEST_SNIPPET};\n" + content[idx:]
|
|
||||||
with open(default_site, "w") as f:
|
|
||||||
f.write(new_content)
|
|
||||||
print(f"Included snippet in {default_site}")
|
|
||||||
|
|
||||||
if run_cmd(["sudo", "nginx", "-t"]):
|
|
||||||
run_cmd(["sudo", "systemctl", "reload", "nginx"])
|
|
||||||
print("Nginx reloaded with snippet successfully.")
|
|
||||||
else:
|
else:
|
||||||
print("Nginx test failed, check configuration.")
|
print(f"Nginx config test failed: {test_res.stderr}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error configuring Nginx: {e}")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == '__main__':
|
||||||
configure_nginx()
|
main()
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,21 @@
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=CRM Django Backend Service
|
Description=CRM Backend Service
|
||||||
After=network.target
|
After=network.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
User=ubuntu
|
User=ubuntu
|
||||||
Group=ubuntu
|
|
||||||
WorkingDirectory=/home/ubuntu/crmbackend
|
WorkingDirectory=/home/ubuntu/crmbackend
|
||||||
EnvironmentFile=/home/ubuntu/crmbackend/.env
|
EnvironmentFile=/home/ubuntu/crmbackend/.env
|
||||||
ExecStart=/home/ubuntu/crmbackend/venv/bin/gunicorn crm.wsgi:application --bind 127.0.0.1:8000 --workers 3 --threads 4 --access-logfile /home/ubuntu/crmbackend/logs/gunicorn-access.log --error-logfile /home/ubuntu/crmbackend/logs/gunicorn-error.log
|
ExecStart=/home/ubuntu/crmbackend/venv/bin/gunicorn crm.wsgi:application \
|
||||||
|
--bind 0.0.0.0:8081 \
|
||||||
|
--workers 3 \
|
||||||
|
--access-logfile /home/ubuntu/crmbackend/logs/gunicorn-access.log \
|
||||||
|
--error-logfile /home/ubuntu/crmbackend/logs/gunicorn-error.log \
|
||||||
|
--log-level info \
|
||||||
|
--capture-output
|
||||||
|
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=3
|
RestartSec=5
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,41 @@
|
||||||
location /crm/ {
|
server {
|
||||||
proxy_pass http://127.0.0.1:8000/;
|
server_name betaapicsa.tradhox.com apicsa.tradhox.com;
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
location / {
|
||||||
proxy_set_header Connection 'upgrade';
|
# Handle CORS preflight requests directly in Nginx
|
||||||
proxy_set_header Host $host;
|
if ($request_method = 'OPTIONS') {
|
||||||
proxy_cache_bypass $http_upgrade;
|
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS, PATCH' always;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
|
||||||
|
add_header 'Access-Control-Max-Age' 1728000 always;
|
||||||
|
add_header 'Content-Type' 'text/plain; charset=utf-8' always;
|
||||||
|
add_header 'Content-Length' 0 always;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy_pass http://127.0.0.1:8081;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
listen 443 ssl; # managed by Certbot
|
||||||
|
ssl_certificate /etc/letsencrypt/live/betaapicsa.tradhox.com/fullchain.pem; # managed by Certbot
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/betaapicsa.tradhox.com/privkey.pem; # managed by Certbot
|
||||||
|
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
|
||||||
|
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
|
||||||
}
|
}
|
||||||
|
|
||||||
location = /crm {
|
server {
|
||||||
return 301 /crm/;
|
if ($host = apicsa.tradhox.com) {
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
if ($host = betaapicsa.tradhox.com) {
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
listen 80;
|
||||||
|
server_name betaapicsa.tradhox.com apicsa.tradhox.com;
|
||||||
|
return 404;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue