<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>FastAPI &#8211; Aveshost Blog</title>
	<atom:link href="https://blog.aveshost.com/tag/fastapi/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.aveshost.com</link>
	<description>Your Blueprint for Online Success</description>
	<lastBuildDate>Thu, 19 Nov 2026 18:40:32 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://blog.aveshost.com/wp-content/uploads/2026/01/logo-150x150.png</url>
	<title>FastAPI &#8211; Aveshost Blog</title>
	<link>https://blog.aveshost.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Deploy FastAPI on an Ubuntu VPS with Nginx and HTTPS</title>
		<link>https://blog.aveshost.com/deploy-fastapi-ubuntu-vps/</link>
					<comments>https://blog.aveshost.com/deploy-fastapi-ubuntu-vps/#respond</comments>
		
		<dc:creator><![CDATA[James Wilson]]></dc:creator>
		<pubDate>Thu, 19 Nov 2026 18:40:00 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Web Hosting]]></category>
		<category><![CDATA[FastAPI]]></category>
		<category><![CDATA[HTTPS]]></category>
		<category><![CDATA[Linux VPS]]></category>
		<category><![CDATA[Nginx]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.aveshost.com/?p=6020</guid>

					<description><![CDATA[Run FastAPI privately behind Nginx, keep it online with systemd, enable HTTPS with Certbot and verify the deployment from application to certificate renewal.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">To <strong>deploy FastAPI</strong> on an Ubuntu VPS, run the application with Uvicorn on <code>127.0.0.1:8000</code>, supervise it with systemd, and put Nginx in front on ports 80 and 443. Nginx terminates HTTPS while the application remains reachable only through the local upstream.</p>



<p class="wp-block-paragraph">Our walkthrough takes a small API from a Python virtual environment to a working domain with a renewable certificate. It uses a dedicated service account and includes checks at each layer, so you can identify a failed application, proxy configuration or certificate challenge separately.</p>



<p class="wp-block-paragraph">Use a fresh Ubuntu 24.04 LTS VPS, SSH access with sudo privileges, and a domain or subdomain you control. Replace <code>api.example.com</code> throughout with your real hostname. This example serves a standard HTTP API at the domain root; it does not configure Docker, WebSockets, streaming, a database or a control-panel-managed Nginx installation.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><div><div><a href="#prepare">1. Prepare the VPS, DNS and firewall</a></div><div><a href="#app">2. Create the application and virtual environment</a></div><div><a href="#systemd">3. Keep FastAPI running with systemd</a></div><div><a href="#nginx">4. Put Nginx in front of FastAPI</a></div><div><a href="#https">5. Enable HTTPS with Certbot</a></div><div><a href="#renewal">6. Verify renewal and external access</a></div><div><a href="#troubleshoot">7. Troubleshoot the failing layer</a></div><div><a href="#maintain">8. Deploy FastAPI updates and plan capacity</a></div><div><a href="#faq">Frequently asked questions</a></div></div></nav></div>



<h2 id="prepare" class="wp-block-heading">1. Prepare the VPS, DNS and firewall</h2>



<p class="wp-block-paragraph">Point the hostname’s A record to the VPS IPv4 address. Add an AAAA record only when IPv6 reaches this same server correctly. Keep an existing SSH connection open and confirm console recovery access before changing firewall policy.</p>



<p class="wp-block-paragraph">Install the packages used below:</p>



<pre class="wp-block-code"><code>sudo apt update
sudo apt install -y python3-venv nginx curl dnsutils ufw snapd
dig +short A api.example.com
dig +short AAAA api.example.com</code></pre>



<p class="wp-block-paragraph">For a new server using SSH on port 22, allow SSH and the web-server ports before enabling UFW:</p>



<pre class="wp-block-code"><code>sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status verbose</code></pre>



<p class="wp-block-paragraph">If SSH uses another port, allow that actual TCP port first. Preserve existing rules on a server already in use. Apply equivalent access rules to any upstream VPS firewall. Do not open port 8000 publicly. Ubuntu’s <a href="https://ubuntu.com/server/docs/how-to/security/firewalls/" rel="noopener">firewall guide</a> explains UFW, and its <a href="https://ubuntu.com/server/docs/how-to/web-services/install-nginx/" rel="noopener">Nginx guide</a> covers the Ubuntu package layout.</p>



<p class="wp-block-paragraph">For this HTTP-01 certificate workflow, the hostname must be publicly reachable on port 80. Incorrect DNS, including a stale AAAA record, can prevent validation. See <a href="https://letsencrypt.org/docs/challenge-types/" rel="noopener">Let’s Encrypt’s challenge requirements</a>.</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1536" height="1024" src="https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-nginx-https-architecture.webp" alt="FastAPI deployment architecture showing Nginx handling HTTPS, localhost Uvicorn, systemd supervision and Certbot renewal." class="wp-image-6022" srcset="https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-nginx-https-architecture.webp 1536w, https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-nginx-https-architecture-300x200.webp 300w, https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-nginx-https-architecture-1024x683.webp 1024w, https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-nginx-https-architecture-768x512.webp 768w" sizes="(max-width: 1536px) 100vw, 1536px" /></figure>



<h2 id="app" class="wp-block-heading">2. Create the application and virtual environment</h2>



<p class="wp-block-paragraph">Create a dedicated system account and project directory. These commands are for a new installation; choose different names if they already exist:</p>



<pre class="wp-block-code"><code>sudo adduser --system --group --home /opt/fastapi fastapi
sudo install -d -o fastapi -g fastapi -m 0755 /opt/fastapi
sudo -u fastapi python3 -m venv /opt/fastapi/.venv
sudo -u fastapi /opt/fastapi/.venv/bin/python -m pip install fastapi uvicorn</code></pre>



<p class="wp-block-paragraph">The <a href="https://docs.python.org/3/library/venv.html" rel="noopener">Python virtual environment</a> keeps application packages separate from Ubuntu’s system Python. For an existing project, install its reviewed, pinned requirements instead of replacing them with this demonstration’s dependencies.</p>



<p class="wp-block-paragraph">Create <code>/opt/fastapi/main.py</code> with <code>sudo nano /opt/fastapi/main.py</code>, paste the following and save:</p>



<pre class="wp-block-code"><code>from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "FastAPI is running"}

@app.get("/health")
async def health():
    return {"status": "ok"}
</code></pre>



<p class="wp-block-paragraph">Run the ASGI server in the foreground:</p>



<pre class="wp-block-code"><code>sudo -u fastapi /opt/fastapi/.venv/bin/uvicorn main:app --app-dir /opt/fastapi --host 127.0.0.1 --port 8000</code></pre>



<p class="wp-block-paragraph">In a second SSH session, run <code>curl -fsS http://127.0.0.1:8000/health</code>. Expect <code>{"status":"ok"}</code>. Stop the foreground server with Ctrl+C before starting systemd, freeing port 8000. FastAPI’s <a href="https://fastapi.tiangolo.com/deployment/manually/" rel="noopener">server documentation</a> explains the application import string.</p>



<h2 id="systemd" class="wp-block-heading">3. Keep FastAPI running with systemd</h2>



<p class="wp-block-paragraph">Create an empty environment file for application settings, readable by root and the service group:</p>



<pre class="wp-block-code"><code>sudo install -o root -g fastapi -m 0640 /dev/null /etc/fastapi.env</code></pre>



<p class="wp-block-paragraph">Later, add required <code>NAME=value</code> settings using <code>sudoedit /etc/fastapi.env</code>. The app must explicitly read those settings; creating the file does not configure a database automatically. Keep credentials out of source control and logs.</p>



<p class="wp-block-paragraph">Create <code>/etc/systemd/system/fastapi.service</code> with <code>sudo nano /etc/systemd/system/fastapi.service</code> and save:</p>



<pre class="wp-block-code"><code>&#91;Unit]
Description=FastAPI application
After=network.target

&#91;Service]
User=fastapi
Group=fastapi
WorkingDirectory=/opt/fastapi
EnvironmentFile=/etc/fastapi.env
ExecStart=/opt/fastapi/.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 1 --proxy-headers --forwarded-allow-ips=127.0.0.1
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
PrivateTmp=true

&#91;Install]
WantedBy=multi-user.target
</code></pre>



<p class="wp-block-paragraph">The absolute executable path removes the need to activate the virtual environment. <code>WorkingDirectory</code> lets Uvicorn import <code>main:app</code>. The service runs as the dedicated account and restarts after failure; repeated failures can still hit systemd’s start-rate limits.</p>



<pre class="wp-block-code"><code>sudo systemctl daemon-reload
sudo systemctl enable --now fastapi
sudo systemctl status fastapi --no-pager
curl -fsS http://127.0.0.1:8000/health</code></pre>



<p class="wp-block-paragraph">If it fails, inspect <code>sudo journalctl -u fastapi -n 100 --no-pager</code>. See the <a href="https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html" rel="noopener">systemd service reference</a> for supervision and the <a href="https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html" rel="noopener">execution reference</a> for users, directories and environment files.</p>



<h2 id="nginx" class="wp-block-heading">4. Put Nginx in front of FastAPI</h2>



<p class="wp-block-paragraph">Create <code>/etc/nginx/sites-available/fastapi</code> with <code>sudo nano /etc/nginx/sites-available/fastapi</code>. Use this HTTP configuration first:</p>



<pre class="wp-block-code"><code>server {
    listen 80;
    listen &#91;::]:80;
    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
</code></pre>



<p class="wp-block-paragraph">Enable the site, test syntax, then start or reload Nginx:</p>



<pre class="wp-block-code"><code>sudo ln -s /etc/nginx/sites-available/fastapi /etc/nginx/sites-enabled/fastapi
sudo nginx -t
sudo systemctl enable --now nginx
sudo systemctl reload nginx
curl -fsS http://api.example.com/health</code></pre>



<p class="wp-block-paragraph">Create the symlink only once. On a server hosting other sites, preserve their files and avoid duplicate <code>server_name</code> entries. If IPv6 is disabled at the OS level, omit the IPv6 listen directive rather than publishing a broken AAAA record.</p>



<p class="wp-block-paragraph">The <a href="https://nginx.org/en/docs/http/ngx_http_proxy_module.html" rel="noopener">Nginx proxy module</a> forwards requests to Uvicorn. This single-edge-proxy example overwrites incoming forwarded headers with values from Nginx’s connection; a CDN or additional load balancer requires a separate trusted-proxy design.</p>



<p class="wp-block-paragraph">Uvicorn trusts proxy headers only from <code>127.0.0.1</code> in our service command. Once HTTPS is enabled, that lets FastAPI build correct HTTPS redirects. Avoid trusting every source with a wildcard. FastAPI’s <a href="https://fastapi.tiangolo.com/advanced/behind-a-proxy/" rel="noopener">proxy guide</a> explains the trust boundary.</p>



<h2 id="https" class="wp-block-heading">5. Enable HTTPS with Certbot</h2>



<p class="wp-block-paragraph">Confirm the public HTTP hostname returns the health response before requesting a certificate. The endpoint is a harmless demonstration; do not send credentials or sensitive data over HTTP.</p>



<p class="wp-block-paragraph">This fresh-server workflow uses Certbot’s snap installation. If Certbot already exists through apt or another method, follow its migration instructions instead of mixing installations. Install the snap, then use its explicit executable path:</p>



<pre class="wp-block-code"><code>sudo snap install --classic certbot
sudo /snap/bin/certbot --nginx --redirect -d api.example.com</code></pre>



<p class="wp-block-paragraph">Follow the prompts for an account email and the certificate authority’s terms. Certbot’s Nginx plugin obtains the certificate and updates the selected site to serve HTTPS and redirect HTTP. Back up an existing Nginx configuration before letting it edit that configuration.</p>



<p class="wp-block-paragraph">Check the result without bypassing certificate verification:</p>



<pre class="wp-block-code"><code>sudo nginx -t
curl -fsS https://api.example.com/health
curl -fsS https://api.example.com/openapi.json</code></pre>



<p class="wp-block-paragraph">Visit <code>https://api.example.com/docs</code> and confirm the API documentation loads. HTTPS encrypts transport; it does not authenticate your API’s users. Add the access controls your real endpoints need. The <a href="https://certbot.eff.org/instructions?ws=nginx&amp;os=snap&amp;tab=standard" rel="noopener">official Certbot instructions</a> cover installation and issuance.</p>



<h2 id="renewal" class="wp-block-heading">6. Verify renewal and external access</h2>



<p class="wp-block-paragraph">Test automatic renewal and inspect the scheduled jobs:</p>



<pre class="wp-block-code"><code>sudo /snap/bin/certbot renew --dry-run
systemctl list-timers --all
sudo ss -ltnp</code></pre>



<p class="wp-block-paragraph">Confirm the Certbot renewal timer is present and scheduled. A successful initial certificate does not prove future renewal will work. Keep the required challenge route reachable and monitor expiry independently.</p>



<p class="wp-block-paragraph">In the listening-socket output, Uvicorn should use <code>127.0.0.1:8000</code>; Nginx should own the public web listeners. From a workstation outside the VPS, check HTTPS by hostname and verify that port 8000 is unreachable. Test IPv6 separately if the hostname has an AAAA record.</p>



<p class="wp-block-paragraph">Make a normal API request after a planned reboot and confirm <code>systemctl is-active fastapi nginx</code> reports both services active. The demo health route checks only the process’s HTTP response. For a database-backed app, design readiness checks that also validate critical dependencies without exposing secrets.</p>



<figure class="wp-block-image size-full"><img decoding="async" width="1536" height="1024" src="https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-deployment-checks.webp" alt="Four FastAPI deployment checks covering application health, systemd, Nginx configuration and HTTPS certificate renewal." class="wp-image-6023" srcset="https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-deployment-checks.webp 1536w, https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-deployment-checks-300x200.webp 300w, https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-deployment-checks-1024x683.webp 1024w, https://blog.aveshost.com/wp-content/uploads/2026/11/fastapi-deployment-checks-768x512.webp 768w" sizes="(max-width: 1536px) 100vw, 1536px" /></figure>



<h2 id="troubleshoot" class="wp-block-heading">7. Troubleshoot the failing layer</h2>



<p class="wp-block-paragraph">Diagnose from the application outward. If localhost is failing, changing DNS or requesting another certificate will not repair the Python process.</p>



<p class="wp-block-paragraph">Useful logs are <code>sudo journalctl -u fastapi -n 100 --no-pager</code> and <code>sudo tail -n 100 /var/log/nginx/error.log</code>. Redact tokens, cookies and personal data before sharing them. Avoid repeatedly retrying certificate issuance while DNS or network access is still broken.</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>Symptom</th><th>Check first</th><th>Likely action</th></tr></thead><tbody><tr><td>502 Bad Gateway</td><td>Local health URL and service logs</td><td>Fix import, dependency, process or upstream port</td></tr><tr><td>Nginx welcome page</td><td>DNS and enabled server_name</td><td>Route the hostname to the intended site</td></tr><tr><td>Redirect uses HTTP</td><td>Forwarded scheme and trusted proxy IP</td><td>Keep Nginx headers and Uvicorn trust aligned</td></tr><tr><td>Certificate validation fails</td><td>Public DNS, port 80 and AAAA record</td><td>Correct the challenge path and network reachability</td></tr><tr><td>413 or streaming/WebSocket issues</td><td>Nginx body limits, buffering and upgrade settings</td><td>Configure the application-specific proxy behavior</td></tr></tbody></table></figure>



<h2 id="maintain" class="wp-block-heading">8. Deploy FastAPI updates and plan capacity</h2>



<p class="wp-block-paragraph">For application updates, retain a known working release and dependency set, run your tests, deploy the reviewed code, and restart <code>sudo systemctl restart fastapi</code>. Recheck local and public health endpoints. Run <code>daemon-reload</code> before restarting if the unit file changes. A restart can briefly interrupt requests; this single-server setup does not provide zero-downtime releases.</p>



<p class="wp-block-paragraph">Start with the one worker shown. Increase workers only after measuring CPU, memory and database-connection usage. Each process has its own memory and application state; background tasks or startup jobs may run in each worker. Use shared persistent storage and appropriate job coordination. See <a href="https://fastapi.tiangolo.com/deployment/server-workers/" rel="noopener">FastAPI’s worker guidance</a>.</p>



<p class="wp-block-paragraph">Protect production documentation and administrative endpoints as appropriate, back up persistent data off-server, monitor errors and disk growth, and keep Ubuntu and dependencies maintained. The empty environment-file creation command is a first-install step; do not rerun it over a populated settings file.</p>



<p class="wp-block-paragraph">Our <a href="https://www.aveshost.com/self-managed-vps-hosting" rel="noopener">self-managed VPS hosting</a> suits teams that want control of this stack. Size the server for your actual workload and management needs; <a href="https://www.aveshost.com/support" rel="noopener">contact our support team</a> to discuss the deployment. Our <a href="https://blog.aveshost.com/docker-disk-space-full/">VPS storage troubleshooting guide</a> is useful when logs or deployment artifacts fill a server.</p>



<h2 id="faq" class="wp-block-heading">Frequently asked questions</h2>


<div id="rank-math-faq" class="rank-math-block">
<div class="rank-math-list ">
<div id="faq-question-60f4db7d85054bdcba3bc74e43dfab88" class="rank-math-list-item">
<h3 class="rank-math-question ">Do I need Gunicorn to deploy FastAPI on a VPS?</h3>
<div class="rank-math-answer ">

<p>No. This setup uses Uvicorn directly under systemd. Uvicorn can run worker processes itself; choose a process model based on measured load and memory rather than adding a second manager automatically.</p>

</div>
</div>
<div id="faq-question-367e44d8e9f34581b2fec6553a27e78c" class="rank-math-list-item">
<h3 class="rank-math-question ">Should I run Uvicorn with &#8211;reload in production?</h3>
<div class="rank-math-answer ">

<p>No. Reload mode is intended for development. Deploy a reviewed release and restart the supervised service deliberately. Keep the application bound to localhost behind Nginx.</p>

</div>
</div>
<div id="faq-question-da375db5144f418ebdc4a51cc8e22f9b" class="rank-math-list-item">
<h3 class="rank-math-question ">Why does FastAPI work on localhost but return 502 through Nginx?</h3>
<div class="rank-math-answer ">

<p>Compare proxy_pass with the actual listening address and port, then inspect Nginx’s error log. Verify the enabled site configuration and whether the app is still running when the proxy request arrives.</p>

</div>
</div>
<div id="faq-question-2611c4d5ca7245adbf70539d9caa94c1" class="rank-math-list-item">
<h3 class="rank-math-question ">Does my API need its own certificate inside Uvicorn?</h3>
<div class="rank-math-answer ">

<p>Not in this same-host design. Nginx handles public HTTPS and forwards HTTP over loopback. If the upstream moves to another server or network, reassess encryption and trust for that connection.</p>

</div>
</div>
<div id="faq-question-afe3015930f04fd191e483a589b6f5b0" class="rank-math-list-item">
<h3 class="rank-math-question ">Can I deploy an existing database-backed FastAPI project this way?</h3>
<div class="rank-math-answer ">

<p>Yes, but add its pinned dependencies, environment settings, database connectivity, migrations, backups and readiness checks. Preserve persistent data outside disposable releases and plan rollback around schema compatibility.</p>

</div>
</div>
</div>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://blog.aveshost.com/deploy-fastapi-ubuntu-vps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
