Running a Self-Hosted AI Agent on Your Own Linux VPS with Docker and Nginx

Running a Self-Hosted AI Agent on Your Own Linux VPS with Docker and Nginx

Z
Zahid Hasan Tonmoy
November 21, 2026
12 min read
🇧🇩 বাংলায় পড়ুন
|
0 views
Audio Overview & Podcast
~1 min quick overview
0%

Running a Self-Hosted AI Agent on Your Own Linux VPS with Docker and Nginx

In our previous guide on deploying your Next.js and Python AI agent projects to Vercel, we configured maxDuration: 60 and region co-location to ship our DevPulse workspace on serverless infrastructure. Serverless platforms are fantastic when your agent finishes every turn within a minute, but what happens when you build an autonomous research agent that needs four minutes to crawl ten documentation pages, run headless Playwright browser checks, maintain persistent in-memory worker queues, or process thousands of daily requests on a predictable $6/month flat server bill?

To run a self-hosted AI agent reliably on your own Linux VPS, you package your Next.js standalone app and Python FastAPI service into multi-stage Docker containers running under non-root Linux users, orchestrate them alongside a local Redis instance via docker-compose.yml, and place an Nginx reverse proxy in front configured with proxy_buffering off and proxy_read_timeout 300s. This architecture eliminates serverless execution timeouts completely, keeps internal microservice traffic isolated on a private Docker bridge network, and streams Server-Sent Events (SSE) over HTTPS with zero per-invocation cloud markups.

Today, in Post 31 of our 62-part series, we take the exact Next.js and Python FastAPI agent stack we built across Posts 13 to 30 and containerize it for production on a self-managed Ubuntu VPS.

When You Should Move Your AI Agent from Serverless to a Docker VPS

Moving from a managed platform like Vercel to your own Virtual Private Server (such as Hetzner Cloud, DigitalOcean Droplets, AWS Lightsail, or Linode) is an engineering trade-off. You take on container maintenance in exchange for four major capabilities that serverless environments restrict:

  1. Zero Arbitrary Execution Timeouts: On a VPS, you control the socket timeout. If a deep multi-step LangChain or Python agent needs 180 seconds to analyze a massive pull request and run diagnostic scripts, Nginx and Uvicorn will hold the SSE stream open as long as you configure them to.
  2. Persistent Local State and Zero-Latency Redis: Instead of paying per HTTP command to an external serverless Redis provider, you can run an official redis:7-alpine container on the exact same VPS. Your rate limiter and session cache communicate over a local Docker socket in 0.1 milliseconds for $0 extra cost.
  3. System-Level Dependencies (Playwright, FFmpeg, OCR): When an agent tool needs Chromium for web scraping, poppler for PDF parsing, or local C++ binaries, installing them inside a custom Dockerfile takes one apt-get install line—whereas stuffing them into a 250MB serverless lambda bundle is painful.
  4. Predictable Flat-Rate Pricing: A 2-vCPU, 4GB RAM Ubuntu VPS costs roughly $5 to $12 per month fixed. Even if your agent handles 50,000 long-running streaming connections a month, your hosting bill never spikes.

3D glassmorphism visualization of a Linux VPS running an Nginx reverse proxy gate in front of isolated Next.js, Python FastAPI, and Redis Docker containers
3D glassmorphism visualization of a Linux VPS running an Nginx reverse proxy gate in front of isolated Next.js, Python FastAPI, and Redis Docker containers

The Self-Hosted Docker VPS Architecture

In a production VPS setup, you should never expose Node.js (port 3000), Uvicorn (port 8000), or Redis (port 6379) directly to the public internet. Only your reverse proxy (Nginx or Caddy) listens on public ports 80 and 443, while all agent containers talk to each other inside an isolated Docker bridge network (agent-net).

Here is how incoming requests flow through our containerized VPS stack:

mermaid graph TD A[Developer Browser / Webhook Client] -->|HTTPS Port 443| B[Ubuntu VPS Firewall: UFW 80/443 Only] B --> C[Nginx Reverse Proxy Container: proxy_buffering off] C -->|/ UI & /api/chat| D[Next.js Standalone Container: Port 3000] C -->|/api/v1/agent/stream| E[Python FastAPI Uvicorn Container: Port 8000] D -->|0.1ms Internal TCP| F[(Local Redis 7 Alpine Container: Port 6379)] E -->|0.1ms Internal TCP| F D -->|Outbound HTTPS| G[Supabase pgvector + OpenAI / Claude APIs] E -->|Outbound HTTPS| G Architecture Flow Summary: Client HTTPS Request → Ubuntu UFW Firewall (443) → Nginx Reverse Proxy Container (Unbuffered SSE) → Isolated Docker Network (Next.js Standalone + Python FastAPI + Local Redis 7) → Outbound LLM & Supabase Vector APIs.

Zahid's Engineering Perspective: The 1.4GB Docker Image OOM Crash and the 127.0.0.1 Trap

When I was configuring deployment scripts and container workflows across Linux environments for my full-stack projects, I learned the hard way that a Dockerfile that works on a 16GB RAM laptop can easily crash a budget 2GB RAM Linux VPS.

In my first attempt to containerize our Next.js + Python agent stack on an Ubuntu VPS, I made two classic mistakes. First, for the Next.js container, I used a single-stage FROM node:20 image that copied the entire node_modules folder and ran npm run build directly on the VPS without enabling Next.js output: 'standalone'. Halfway through the TypeScript compilation on the VPS, the Linux Out-Of-Memory (OOM) killer terminated the build with exit code 137, and the resulting image was a bloated 1.42GB! Adding a 2GB Linux swap file on the host and switching to a **multi-stage node:20-alpine build with output: 'standalone'** shrank the final production container image from 1.42GB down to 158MB.

Second, when I started my Python FastAPI container with uvicorn main:app --port 8000, the container logs said Uvicorn running on [http://127.0.0.1:8000](http://127.0.0.1:8000)—yet Nginx kept returning 502 Bad Gateway! Why? Because inside a Docker container, 127.0.0.1 refers only to that single container's private loopback interface, making it unreachable from the Nginx container next door. Changing the bind address to --host 0.0.0.0 --port 8000 immediately allowed Nginx to route traffic across the Docker bridge network.

Step 1: Production Multi-Stage Dockerfile for the Python FastAPI Agent

Let us start with our Python FastAPI service (devpulse-python-agent from Posts 28 and 29). Create a Dockerfile inside the Python directory that installs dependencies in a clean wheel stage, creates a non-root Linux user (agentuser) for security, binds Uvicorn to 0.0.0.0, and includes a built-in Docker HEALTHCHECK:

`dockerfile

devpulse-python-agent/Dockerfile

FROM python:3.12-slim AS builder

WORKDIR /build ENV PYTHONDONTWRITEBYTECODE=1
PYTHONUNBUFFERED=1

RUN apt-get update && apt-get install -y --no-install-recommends
build-essential
&& rm -rf /var/lib/apt/lists/*

COPY requirements.txt . RUN pip install --upgrade pip &&
pip wheel --no-cache-dir --no-deps --wheel-dir /build/wheels -r requirements.txt

FROM python:3.12-slim AS runner

WORKDIR /app ENV PYTHONDONTWRITEBYTECODE=1
PYTHONUNBUFFERED=1

RUN apt-get update && apt-get install -y --no-install-recommends
curl
&& rm -rf /var/lib/apt/lists/*
&& groupadd -r agentgroup && useradd -r -g agentgroup agentuser

COPY --from=builder /build/wheels /wheels RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels

COPY --chown=agentuser:agentgroup . .

USER agentuser EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3
CMD curl -f http://localhost:8000/health || exit 1

CMD ['uvicorn', 'main:app', '--host', '0.0.0.0', '--port', '8000', '--workers', '2', '--timeout-keep-alive', '75'] `

Notice three production details in this Dockerfile:

  1. PYTHONUNBUFFERED=1: Prevents Python from buffering stdout and stderr, ensuring your real-time agent logs appear immediately when you run docker compose logs -f.
  2. Non-Root Execution (USER agentuser): If an attacker ever exploits a dependency vulnerability inside a custom tool, the process has zero root privileges inside the container.
  3. --host 0.0.0.0: Binds Uvicorn to all network interfaces inside the container so our Nginx container can reach port 8000.

Step 2: Production Multi-Stage Dockerfile for the Next.js Agent Workspace

Before containerizing your Next.js app, open next.config.ts (or next.config.mjs) and enable standalone output mode:

`typescript // next.config.ts import type { NextConfig } from 'next';

const nextConfig: NextConfig = { output: 'standalone', };

export default nextConfig; `

When output: 'standalone' is enabled, npm run build traces only the exact files needed for production and outputs a self-contained server.js file inside .next/standalone that runs without the massive node_modules tree. Now create Dockerfile in your Next.js project root:

`dockerfile

devpulse-nextjs/Dockerfile

FROM node:20-alpine AS deps WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci

FROM node:20-alpine AS builder WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . ENV NEXT_TELEMETRY_DISABLED=1 RUN npm run build

FROM node:20-alpine AS runner WORKDIR /app ENV NODE_ENV=production
NEXT_TELEMETRY_DISABLED=1
PORT=3000
HOSTNAME='0.0.0.0'

RUN addgroup --system --gid 1001 nodejs &&
adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs EXPOSE 3000

CMD ['node', 'server.js'] `

Step 3: Orchestrating the Stack with docker-compose.yml

Now let us create docker-compose.yml on our VPS to unite the Next.js workspace, the Python FastAPI agent, a local Redis 7 cache, and an Nginx reverse proxy on a single internal bridge network (agent-net).

`yaml

docker-compose.yml

services: redis-cache: image: redis:7-alpine container_name: devpulse-redis restart: unless-stopped command: redis-server --save 60 1 --loglevel warning --maxmemory 128mb --maxmemory-policy allkeys-lru volumes: - redis_data:/data networks: - agent-net

python-agent: build: context: ./devpulse-python-agent dockerfile: Dockerfile container_name: devpulse-python-api restart: unless-stopped env_file: - ./.env.production environment: - REDIS_URL=redis://redis-cache:6379/0 depends_on: - redis-cache deploy: resources: limits: memory: 512M networks: - agent-net

nextjs-agent: build: context: ./devpulse-nextjs dockerfile: Dockerfile container_name: devpulse-nextjs-ui restart: unless-stopped env_file: - ./.env.production environment: - PYTHON_AGENT_INTERNAL_URL=http://python-agent:8000 depends_on: - python-agent - redis-cache deploy: resources: limits: memory: 768M networks: - agent-net

nginx-proxy: image: nginx:1.27-alpine container_name: devpulse-nginx restart: unless-stopped ports: - '80:80' - '443:443' volumes: - ./nginx/agent.conf:/etc/nginx/conf.d/default.conf:ro depends_on: - nextjs-agent - python-agent networks: - agent-net

networks: agent-net: driver: bridge

volumes: redis_data: `

Look closely at how nextjs-agent communicates with python-agent: because both containers share the agent-net Docker bridge network, Next.js can call http://python-agent:8000/api/v1/agent/stream directly over Docker's internal DNS without traversing the public internet!

Step 4: Configuring Nginx for Unbuffered AI Agent Streaming (nginx/agent.conf)

As we discovered back in Post 23 when building our SSE pipeline, default Nginx settings buffer upstream responses—which destroys real-time token streaming. Create nginx/agent.conf with proxy_buffering off;, proxy_cache off;, and an extended 300-second read timeout (proxy_read_timeout 300s;) so long multi-step agent runs never get cut off:

`nginx

nginx/agent.conf

upstream nextjs_upstream { server nextjs-agent:3000; keepalive 32; }

upstream python_agent_upstream { server python-agent:8000; keepalive 32; }

server { listen 80; server_name agent.yourdomain.com;

location /api/v1/agent/ {
    proxy_pass http://python_agent_upstream;
    proxy_http_version 1.1;
    proxy_set_header Connection '';
    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_buffering off;
    proxy_cache off;
    chunked_transfer_encoding on;
    tcp_nopush on;
    tcp_nodelay on;
    proxy_read_timeout 300s;
    proxy_send_timeout 300s;
}

location / {
    proxy_pass http://nextjs_upstream;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    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_buffering off;
    proxy_cache off;
    proxy_read_timeout 300s;
}

} `

To launch the entire stack on your Ubuntu VPS, SSH into your server, ensure a 2GB swap file is active, and run:

`bash

Build and start all 4 containers in detached mode

docker compose up -d --build

Inspect live container health and resource usage

docker compose ps docker stats --no-stream `

Dark frosted glass multi-stage Docker build pipeline compressing a bulky container block into a compact glowing crystal module with an emerald healthcheck ring
Dark frosted glass multi-stage Docker build pipeline compressing a bulky container block into a compact glowing crystal module with an emerald healthcheck ring

Common Mistakes When Self-Hosting AI Agents with Docker

Before pointing your production DNS A record to your VPS IP address, verify that your setup avoids these 4 critical self-hosting mistakes:

  1. Baking .env.production Inside the Docker Image Layer (COPY .env .): Never copy secret .env files inside a Dockerfile. Anyone who gains access to your container registry or runs docker history can extract your OpenAI, Anthropic, and Supabase keys. Always inject secrets at runtime via env_file: ./.env.production in docker-compose.yml and add .env* to .dockerignore.
  2. Leaving Nginx proxy_buffering at Its Default (on): By default, Nginx buffers upstream packets from FastAPI and Next.js until its internal memory buffer fills up. Omitting proxy_buffering off; and proxy_set_header Connection ''; causes your 300ms token stream to freeze for 6 seconds and dump all at once.
  3. **Publishing Internal Database or Redis Ports to 0.0.0.0**: Never write ports: ['6379:6379'] on your Redis container in docker-compose.yml unless bound strictly to 127.0.0.1:6379:6379. Because Docker modifies iptables directly, publishing port 6379 exposes your Redis store to the public internet—bypassing ufw firewall rules!
  4. Running docker compose build on a 1GB/2GB VPS Without Swap Memory: Compiling Next.js TypeScript bundles inside Docker peaks at 1.2GB to 1.8GB of RAM. On a small VPS without a swap file (fallocate -l 2G /swapfile), the Linux kernel will silently kill the build (SIGKILL / exit 137). Always enable a 2GB swap file and enforce container memory limits.

Frequently Asked Questions

How much VPS RAM and CPU do I actually need to self-host this Next.js + FastAPI + Redis agent stack?

Because heavy neural network inference still runs on OpenAI's and Anthropic's GPU clusters via API, your VPS only handles async HTTP I/O, Pydantic/Zod validation, and SSE stream routing. A 2 vCPU, 2GB to 4GB RAM Ubuntu 24.04 VPS (costing ~$5–$8/month on Hetzner or DigitalOcean) comfortably handles dozens of concurrent streaming users when built with Next.js output: 'standalone' and python:3.12-slim.

Why use Nginx (or Caddy) in front of Next.js and FastAPI instead of exposing port 3000 directly?

A dedicated reverse proxy handles TLS/HTTPS certificate termination (Let's Encrypt), routes /api/v1/agent/* requests to Python and / requests to Next.js on the same domain (eliminating cross-origin CORS preflight overhead!), enforces X-Forwarded-For headers for our rate limiter, and shields your application containers from slowloris socket attacks.

How do I deploy code updates to my Docker VPS without long downtime?

Pull the latest Git commit on your VPS (git pull origin main) and run docker compose up -d --build. Docker caches unchanged dependency layers (wheels and npm ci) so rebuilding takes only 15–30 seconds, and Compose only recreates the containers whose code changed—a workflow we will automate completely with GitHub Actions CI/CD in Post 36!

🟢 Available for Freelance & Contract Work

Need a High-Performance Web App or Custom AI Solution?

I help founders, businesses, and engineering teams build lightning-fast web applications, resilient backend architectures, and intelligent AI workflows. Have an idea in mind? Let’s bring it to life.

Fast MVP Launch (2–4 weeks)
AI Agent & LLM API Integration
100/100 Core Web Vitals & SEO
Production-Ready Clean Architecture

Found this article helpful?

Give some claps to support more in-depth engineering logs!

0 views
Z

Zahid Hasan Tonmoy

Author & Developer

MERN Full Stack Developer & AI Agent Developer based in Dhaka, Bangladesh. Writing about web development, React, PostgreSQL and my learning journey.

Related Articles

Stay Updated

Subscribe to get insights on full-stack architecture, AI agent engineering, and web development.