How to Change the Port in FastAPI – Quick Step‑by‑Step Guide
Changing your FastAPI port is something many developers run into the first time they move a prototype out of the default 8000 sandbox. Whether you’re avoiding a clash with another service, complying with a corporate firewall, or just preferring a cleaner URL, the process is straightforward once you know where to look. Below we’ll walk through the most common methods, touch on container‑based deployments, and flag a few gotchas that can trip you up.
Why Change the Default Port?
The default 8000 port works perfectly for local tinkering, but production environments often demand something else. A non‑standard port can keep your API out of the way of other web services running on the same host, and some cloud providers even require you to bind to a specific port for health checks. Additionally, using a well‑known port like 80 or 443 lets you hide the fact that you’re serving a FastAPI app behind a reverse proxy, which can look more polished to end users.
Basic Ways to Set a New Port
Using the uvicorn CLI
The quickest method is to tell uvicorn what port to listen on when you start the server. The syntax is simple:
uvicorn myapp:app --host 0.0.0.0 --port 8080Replace myapp:app with the module path to your FastAPI instance, and swap 8080 for whatever number fits your network policy. The --host 0.0.0.0 flag makes the service reachable from other machines, which is usually what you want in a dev‑or‑test scenario.
Setting the Port Programmatically
If you prefer to keep the launch command tidy or need to switch ports based on an environment variable, you can start uvicorn from within Python:
import osimport uvicorn
if __name__ == "__main__":
port = int(os.getenv("FASTAPI_PORT", 8000))
uvicorn.run("myapp:app", host="0.0.0.0", port=port)
Now you can control the port with FASTAPI_PORT=8080 python run.py. This approach is handy for Docker images or CI pipelines where you don’t want to hard‑code values.
Running Behind a Proxy or Docker
In many production stacks, FastAPI sits behind Nginx, Traefik, or another reverse proxy. The proxy forwards external traffic (often on 80 or 443) to the internal port your FastAPI app listens on. In that case, you still need to tell FastAPI its own port, but the external URL that users see can stay conventional.
When you containerise the app, the EXPOSE directive in the Dockerfile should match the port you run inside the container:
FROM python:3.11-slimWORKDIR /app
COPY . .
RUN pip install -r requirements.txt
EXPOSE 8080
CMD ["uvicorn", "myapp:app", "--host", "0.0.0.0", "--port", "8080"]
Outside the container, you map that internal port to any host port you like with -p, for example -p 80:8080 to expose it on the standard web port.
Common Pitfalls and How to Avoid Them
- Port already in use. If you get an “address already in use” error, double‑check with
netstat -tulpn(Linux) orlsof -i :8080(macOS) to see what’s occupying the slot. - Binding to
127.0.0.1only. Using--host 127.0.0.1restricts access to the local machine, which is fine for personal scripts but will block remote clients in a team environment. - Forgetting to update environment files. If you rely on a
.envfile, make sure the variable name matches your code (FASTAPI_PORTin the example) and that the file is loaded before the server starts. - Mismatched proxy configuration. Your reverse proxy must forward to the exact internal port. A typo in the Nginx
proxy_passline (e.g.,http://localhost:8000instead of8080) will produce a 502 Bad Gateway error.
Testing the New Port
Once you’ve started the server on a new port, a quick curl request confirms everything’s listening:
curl -i http://localhost:8080/docsIf you see the OpenAPI Swagger UI HTML, the port change succeeded. For remote machines, replace localhost with the host’s IP address or domain name.
When to Stick With the Default
There are scenarios where changing the port adds no real benefit. For isolated development containers, the default 8000 keeps documentation and tutorials consistent. Likewise, if you’re the sole user on a machine and no other services need that slot, the extra step might feel unnecessary. Use your judgment; the goal is to keep the workflow smooth, not to over‑engineer.
FAQ
Can I change the port without restarting the server?
No. The listening socket is bound when the process starts, so you need to stop the server and start it again with the new --port value or updated environment variable.
Is it safe to expose FastAPI on port 80 or 443 directly?
It’s technically possible, but you’ll miss out on TLS termination that a reverse proxy typically provides. Exposing HTTPS directly also requires you to manage certificates inside the FastAPI process, which adds complexity.
Do I need to change anything in settings.py when I switch ports?
Only if you store the port number there for reference elsewhere (e.g., in generated URLs). Otherwise, the port lives solely in the server launch command or environment variable.
What happens if I set a port below 1024?
On Unix‑like systems, ports under 1024 are privileged and require root permissions. Running a web server as root is discouraged, so most developers opt for higher, unprivileged ports unless a proxy handles the low‑port binding.