October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk8 min

How to Create a FastAPI App Using Docker Compose on a VPS

A practical production layout for FastAPI on a VPS: run one Uvicorn process per container, keep port 8000 private, and let Caddy handle HTTPS on ports 80 and 443.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The dependable production layout is a two-service Compose project: a FastAPI container listens only on the private Compose network, while a reverse proxy such as Caddy owns ports 80 and 443, obtains HTTPS certificates, and forwards requests to the API. Build the image on the VPS, keep configuration in an .env file, add restart: unless-stopped, and start the stack with docker compose up -d.

FastAPI’s current container guidance favors one Uvicorn process per container and scaling by adding containers. Read the official guidance at FastAPI in Containers – Docker. The older tiangolo/uvicorn-gunicorn-fastapi-docker image is deprecated; use a normal Python base image and the official FastAPI container pattern instead.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What you will deploy

Your VPS will run two Compose services on one private network:

  • api: your FastAPI application, listening on port 8000 inside its container. It has no public port mapping.
  • caddy: the public reverse proxy. It publishes ports 80 and 443, terminates TLS, and proxies traffic to api:8000.

Only the proxy needs a public address. This prevents clients from bypassing HTTPS or the proxy’s routing rules. The same arrangement works with Traefik or Nginx, but Caddy has the smallest configuration for one domain.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Prerequisites on the VPS

  • A Linux VPS with a public IPv4 address and a DNS name you control, such as api.example.com.
  • Docker Engine and the Docker Compose plugin installed from your distribution or Docker’s installation instructions.
  • TCP ports 80 and 443 allowed by the VPS provider and host firewall, plus SSH access for administration.
  • A project containing your FastAPI source, a Dockerfile, a dependency file, a Compose file, a Caddyfile, and an environment file.

Point the domain’s A record at the VPS before starting Caddy. Automatic certificate issuance requires that the domain resolve to this machine and that the proxy be reachable on ports 80 and 443.

Create the FastAPI application

Use this minimal layout:

fastapi-compose-vps/
├── app/
│   └── main.py
├── requirements.txt
├── Dockerfile
├── compose.yaml
├── Caddyfile
└── .env

Write the application module

Create app/main.py:

from fastapi import FastAPI

app = FastAPI(title='VPS API')

@app.get('/health')
def health():
    return {'status': 'ok'}

@app.get('/')
def read_root():
    return {'message': 'FastAPI is running'}

The import path is significant. With this file, the application object is app.main:app. FastAPI’s CLI command used below points to the file directly, so the container does not need a custom module path at startup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Declare dependencies

Put the FastAPI package with its standard command-line and server extras in requirements.txt:

fastapi[standard]

For repeatable releases, replace the floating dependency with versions you have tested and rebuild the image whenever the file changes.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Build a production-friendly Docker image

Create Dockerfile:

FROM python:3.12-slim

WORKDIR /code

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app ./app

EXPOSE 8000
CMD fastapi run app/main.py --proxy-headers --port 8000

The official example uses fastapi run app/main.py --proxy-headers --port 80. This version uses 8000 so the internal port is explicit in Compose; either port is valid if every reference matches. The --proxy-headers option is important when TLS is terminated by Caddy or another proxy: it lets FastAPI/Uvicorn use the forwarded scheme and client information when generating URLs and handling request metadata.

EXPOSE documents the container port; it does not publish that port on the VPS. Public exposure is controlled in the Compose file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure Compose so only the proxy is public

Create compose.yaml:

services:
  caddy:
    image: caddy:2
    restart: unless-stopped
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile:ro
      - caddy_data:/data
      - caddy_config:/config
    depends_on:
      - api

  api:
    build: .
    restart: unless-stopped
    env_file: .env
    expose:
      - '8000'

volumes:
  caddy_data:
  caddy_config:

expose makes port 8000 available to other services on the Compose network without binding it to the VPS. Do not add 8000:8000 under api.ports unless you intentionally want to bypass the proxy.

restart: unless-stopped brings both containers back after a crash or VPS reboot, while respecting an explicit manual stop. depends_on starts Caddy after the API container is created, but it is not a readiness test; the proxy may briefly return an upstream error while the application is starting.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Keep secrets outside the image

Create .env on the VPS and do not commit it to source control:

APP_ENV=production
DATABASE_URL=postgresql://user:[email protected]/app
SECRET_KEY=replace-with-a-long-random-value

The env_file entry injects these values at runtime, so they are not copied into the image layers. If one value needs a Compose-specific override, add an environment section; inline values take precedence over the file. Restrict the file’s permissions to the deployment account and rotate credentials if the file is exposed.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put Caddy in front of FastAPI for HTTPS

Create a file named Caddyfile beside compose.yaml:

api.example.com {
    reverse_proxy api:8000
}

Replace api.example.com with the DNS name that points to the VPS. Caddy’s official caddy:2 image reads this file, requests a certificate for the site, renews it, and forwards incoming requests to the Compose service name api on port 8000. The named caddy_data volume persists certificates across container recreation; caddy_config persists Caddy’s configuration data.

Mounting the Caddyfile read-only prevents the container from changing the source configuration. Keep ports 80 and 443 published by Caddy only. Port 80 is also needed for HTTP-to-HTTPS handling and certificate challenges, even if all application traffic should ultimately use HTTPS.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Alternative proxies

Proxy Best fit Configuration model Important detail
Caddy One domain or a small stack A short Caddyfile Publishes 80 and 443, stores certificates in persistent volumes, and proxies directly to api:8000.
Traefik Several Compose services with changing routes Docker labels Set exposedByDefault to false so only explicitly labelled containers are routed. A typical deployment mounts the Docker socket read-only and stores Let’s Encrypt state in an acme.json file.
Nginx Teams wanting manual routing and static-file control Handwritten server configuration It can terminate SSL and serve static files, but each route and certificate workflow must be configured explicitly.

Image tags and proxy syntax change over time. Treat caddy:2 and Traefik v3 examples as starting points, verify the current image documentation, and pin a tested tag for a controlled release.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run the stack on the VPS

  1. Install Docker and Compose. Confirm both commands are available with docker --version and docker compose version.
  2. Copy the project. Use Git, an archive transfer, or your deployment system. The directory on the VPS must contain compose.yaml, Dockerfile, Caddyfile, the app directory, and .env.
  3. Set the domain. Create an A record for the hostname in the Caddyfile and wait until public DNS resolves to the VPS address.
  4. Check the proxy file. Ensure the hostname is exact and the upstream is api:8000, not localhost:8000. Inside Caddy, localhost means the Caddy container itself.
  5. Build and start. From the project directory, run:
docker compose up -d --build
  1. Inspect service status.
docker compose ps
  1. Read logs if a service is unhealthy or missing.
docker compose logs -f api
docker compose logs -f caddy
  1. Test the private application from inside the API container.
docker compose exec api python -c "import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8000/health').read().decode())"
  1. Test the public endpoint. Visit https://api.example.com/health. A successful response is JSON containing status set to ok.

When deploying a new revision, copy the changed files and run docker compose up -d --build again. Compose recreates the API container from the new image while preserving the named Caddy volumes.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose one Uvicorn process or multiple workers

Recommended default: one process per container

FastAPI’s Docker guidance recommends one Uvicorn process in each container. This keeps CPU and memory allocation visible to the container scheduler and lets you scale horizontally by adding API containers. For a small VPS, start with one container and measure before adding complexity.

If the service is stateless, you can request additional replicas with:

docker compose up -d --build --scale api=3

All replicas share the Compose network. Confirm that your proxy and application handle multiple upstream addresses correctly, and move sessions, queues, and other shared state to an external service rather than relying on one container’s filesystem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When Gunicorn workers are justified

Gunicorn with Uvicorn workers is an alternative when you specifically need several worker processes inside each container, for example because a single process cannot use the available CPU efficiently. The documented pattern is:

gunicorn app.main:app -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000

Binding to 0.0.0.0 is required for traffic arriving from outside the container. A third-party deployment guide notes that the uvicorn.workers module is being deprecated in favor of the separate uvicorn-worker package; verify the current Uvicorn and Gunicorn documentation before adopting that command. Do not add Gunicorn merely because a template contains it: multiple workers increase memory use and can duplicate startup work.

Diagnose the failures you are most likely to see

Symptom Likely cause Fix
Caddy reports an upstream connection error The API is still starting, crashed, or is listening on a different port. Run docker compose logs api; confirm the command uses port 8000 and that Caddy uses api:8000. Restart after correcting the configuration.
The domain times out DNS still points elsewhere, or ports 80/443 are blocked. Check the A record from an external network and allow both TCP ports in the VPS/provider firewall.
Certificate issuance fails The hostname is not publicly resolvable, port 80 is unavailable, or another service already owns the port. Fix DNS, free ports 80 and 443, then inspect docker compose logs caddy. Keep the caddy_data volume so successful certificates are retained.
FastAPI generates HTTP URLs behind HTTPS Forwarded headers are not trusted by the application process. Ensure the startup command includes --proxy-headers and that the request is actually passing through the configured proxy.
The API is reachable directly on the VPS An accidental ports mapping was added to the API service. Remove that mapping and leave only expose: '8000'; recreate the stack.
Environment values are missing The file path is wrong, the variable name differs, or the container was not recreated. Check that .env is beside compose.yaml, inspect the rendered configuration with docker compose config, and run docker compose up -d --build.
Changes are not visible after deployment The old image is still running. Use docker compose up -d --build; check the image creation time with docker compose images and verify the running container logs.

Operational checklist

  • Use a domain whose A record points to the VPS before starting the proxy.
  • Publish 80 and 443 from Caddy only; keep the FastAPI port internal.
  • Persist Caddy’s /data and /config directories with named volumes.
  • Keep database URLs, signing keys, and other secrets in .env, outside the image and source repository.
  • Use restart: unless-stopped for services that should return after a reboot.
  • Start with one Uvicorn process per API container; scale containers or choose Gunicorn workers only for a measured reason.
  • Review logs after every deployment and test both the public HTTPS health endpoint and the application’s important routes.
  • Pin and periodically update image and Python dependency versions after testing them in a staging environment.

Development and production files

A separate development Compose file can mount source code, enable reload, and use a local environment file, while production keeps the immutable image and public proxy configuration. This split is a convention, not a requirement. If you use it, keep production secrets in a separate file and select the intended file explicitly, for example:

docker compose -f compose.yaml -f compose.production.yaml up -d --build

Do not enable development reload in the production API container: it watches files, consumes extra resources, and is designed for local iteration rather than a continuously running VPS service.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.