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 shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
CONF_SRC = "/tmp/crmbackend.nginx.conf"
|
||||
DEST_CONF_D = "/etc/nginx/conf.d/crmbackend.conf"
|
||||
DEST_SNIPPET = "/etc/nginx/snippets/crmbackend.conf"
|
||||
SITES_AVAILABLE = "/etc/nginx/sites-available"
|
||||
SITES_ENABLED = "/etc/nginx/sites-enabled"
|
||||
def main():
|
||||
source_conf = '/tmp/crmbackend.nginx.conf'
|
||||
target_available = '/etc/nginx/sites-available/crmbackend'
|
||||
target_enabled = '/etc/nginx/sites-enabled/crmbackend'
|
||||
|
||||
def run_cmd(cmd):
|
||||
print(f"Running: {' '.join(cmd)}")
|
||||
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
|
||||
if not os.path.exists(source_conf):
|
||||
source_conf = '/home/ubuntu/crmbackend/crmbackend.nginx.conf'
|
||||
|
||||
def configure_nginx():
|
||||
if not os.path.exists(CONF_SRC):
|
||||
print(f"Warning: {CONF_SRC} not found!")
|
||||
if not os.path.exists(source_conf):
|
||||
print(f"Error: Nginx configuration source file not found at {source_conf}")
|
||||
return
|
||||
|
||||
# Ensure conf.d directory exists
|
||||
os.makedirs("/etc/nginx/conf.d", exist_ok=True)
|
||||
shutil.copy2(CONF_SRC, DEST_CONF_D)
|
||||
print(f"Copied {CONF_SRC} to {DEST_CONF_D}")
|
||||
try:
|
||||
# Copy to sites-available
|
||||
subprocess.run(['sudo', 'cp', source_conf, target_available], check=True)
|
||||
print(f"Copied {source_conf} to {target_available}")
|
||||
|
||||
# Check nginx syntax
|
||||
if run_cmd(["sudo", "nginx", "-t"]):
|
||||
run_cmd(["sudo", "systemctl", "reload", "nginx"])
|
||||
print("Nginx reloaded successfully.")
|
||||
# Enable site symlink
|
||||
if not os.path.exists(target_enabled):
|
||||
subprocess.run(['sudo', 'ln', '-sf', target_available, target_enabled], check=True)
|
||||
print(f"Symlinked {target_available} to {target_enabled}")
|
||||
|
||||
# Test Nginx configuration
|
||||
test_res = subprocess.run(['sudo', 'nginx', '-t'], capture_output=True, text=True)
|
||||
if test_res.returncode == 0:
|
||||
subprocess.run(['sudo', 'systemctl', 'reload', 'nginx'], check=True)
|
||||
print("Nginx configuration verified and reloaded successfully.")
|
||||
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}")
|
||||
print(f"Nginx config test failed: {test_res.stderr}")
|
||||
except Exception as e:
|
||||
print(f"Error configuring Nginx: {e}")
|
||||
|
||||
# Try to include snippet in default site or active sites
|
||||
default_site = os.path.join(SITES_AVAILABLE, "default")
|
||||
if os.path.exists(default_site):
|
||||
with open(default_site, "r") as f:
|
||||
content = f.read()
|
||||
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:
|
||||
print("Nginx test failed, check configuration.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
configure_nginx()
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
|
|||
|
|
@ -1,15 +1,21 @@
|
|||
[Unit]
|
||||
Description=CRM Django Backend Service
|
||||
Description=CRM Backend Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=ubuntu
|
||||
Group=ubuntu
|
||||
WorkingDirectory=/home/ubuntu/crmbackend
|
||||
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
|
||||
RestartSec=3
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
|
|||
|
|
@ -1,15 +1,41 @@
|
|||
location /crm/ {
|
||||
proxy_pass http://127.0.0.1:8000/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
server {
|
||||
server_name betaapicsa.tradhox.com apicsa.tradhox.com;
|
||||
|
||||
location / {
|
||||
# Handle CORS preflight requests directly in Nginx
|
||||
if ($request_method = 'OPTIONS') {
|
||||
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
|
||||
add_header 'Access-Control-Allow-Credentials' 'true' always;
|
||||
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS, PATCH' always;
|
||||
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_cache_bypass $http_upgrade;
|
||||
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 {
|
||||
return 301 /crm/;
|
||||
server {
|
||||
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