Last active
October 29, 2024 18:58
-
-
Save arynyklas/9bab0db9a6ec69a5a5340b022361add0 to your computer and use it in GitHub Desktop.
Run FastAPI with Gunicorn (as a service) through Nginx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from multiprocessing import cpu_count | |
import subprocess | |
import atexit | |
bind = "127.0.0.1:8000" | |
workers = 2 # cpu_count() * 2 + 1 | |
worker_class = "sync" | |
worker_connections = 1024 | |
# NOTE: next lines are optional | |
# used to run background script | |
background_process = subprocess.Popen(["python", "background.py"]) | |
def shutdown_background_process() -> None: | |
background_process.terminate() | |
background_process.wait() | |
atexit.register(shutdown_background_process) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Unit] | |
Description=Project Gunicorn | |
After=network.target | |
[Service] | |
Group=www-data | |
WorkingDirectory=/project/directory | |
Environment="PATH=/project/directory/.venv/bin" | |
ExecStart=/project/directory/.venv/bin/gunicorn -c gunicorn_config.py -k uvicorn.workers.UvicornWorker --bind unix:/tmp/project.sock src:web_app | |
[Install] | |
WantedBy=multi-user.target |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
upstream app_server { | |
server unix:/tmp/project.sock fail_timeout=0; | |
} | |
server { | |
listen 80; | |
server_name project.example.com; | |
return 301 https://$host$request_uri; | |
} | |
server { | |
listen 443 ssl; | |
client_max_body_size 4G; | |
server_name project.example.com; | |
ssl_certificate /etc/ssl/self.pem; | |
ssl_certificate_key /etc/ssl/self.key; | |
keepalive_timeout 5; | |
location / { | |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | |
proxy_set_header X-Forwarded-Proto $scheme; | |
proxy_set_header Host $http_host; | |
proxy_redirect off; | |
proxy_pass http://app_server; | |
} | |
error_log /var/log/nginx/project.example.com-error.log; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- nginx.conf's `user` value must be set to `www-data` (set by default) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment