Sub topic 14
Sharing and deploying your chat app
This chapter assumes you have a working gr.ChatInterface app, can run a Python script, and know what a port is. If you have used a Dockerfile or a Hugging Face account before, the later sections will be quicker. Neither is required.
By default, demo.launch() serves the app only to your own machine. Here you will move from that default to three kinds of sharing: a temporary public link, your own server, and a hosted service. You will also see what changes in each case.
What launch() does by default
Calling launch() starts a web server (Uvicorn, running a FastAPI app) inside your Python process. It binds to 127.0.0.1 on port 7860. Two details matter for deployment:
127.0.0.1is the loopback address. Only processes on the same machine can reach it. A browser on another computer, or on your host when the app runs in a container, cannot.- If port 7860 is taken and you did not set
server_port, Gradio tries 7861, 7862, and so on. If you setserver_portexplicitly and it is busy, launch fails. Pin the port in deployments so that your proxy and firewall rules stay valid.
You can set the address and port with arguments or with environment variables. Environment variables suit containers, because the code stays the same everywhere.
| Setting | `launch()` argument | Environment variable | Default |
|---|---|---|---|
| Bind address | `server_name` | `GRADIO_SERVER_NAME` | `127.0.0.1` |
| Port | `server_port` | `GRADIO_SERVER_PORT` | `7860` |
Choosing a sharing route
Pick by how long the app must live and how much infrastructure you want to run.
Route 1: a temporary share link
The fastest way to show someone your app is one argument:
import gradio as gr
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch(share=True)The terminal prints a local URL and a public URL ending in .gradio.live. Gradio opens a tunnel from your machine to its relay servers, and the relay forwards browser requests to your process.
What this means in practice:
- The app still runs on your computer. Your laptop must stay awake and online. Closing the script ends the link.
- The link expires after a limited time (currently about a week). Treat it as a demo link, not as hosting.
- Anyone who has the URL can use the app. That includes your LLM calls, which are billed to your API key.
- If your network blocks the tunnel,
share=Trueprints a warning and the app keeps running locally.
Route 2: run it on your own server
For your own infrastructure, you need three things: bind to an address the outside can reach, keep secrets out of the code, and control how many requests run at once.
Bind address and secrets
The sixth example in this tutorial's code set already shows the first part: server_name="0.0.0.0" listens on all network interfaces. Here is a deployment-ready app.py that reads everything from the environment:
import os
import gradio as gr
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def respond(message, history):
messages = [{"role": "system", "content": "You are a helpful assistant."}]
messages += [{"role": h["role"], "content": h["content"]} for h in history]
messages.append({"role": "user", "content": message})
stream = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, stream=True
)
reply = ""
for chunk in stream:
reply += chunk.choices[0].delta.content or ""
yield reply
demo = gr.ChatInterface(fn=respond, type="messages")
# Limit load: at most 4 chat calls run at once, 20 more may wait in line.
demo.queue(default_concurrency_limit=4, max_size=20)
if __name__ == "__main__":
demo.launch(
server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"),
server_port=int(os.environ.get("GRADIO_SERVER_PORT", "7860")),
)Concurrency and the queue
Every Gradio event goes through a queue. By default one event function runs up to 1 call at a time per function. For a chat app that waits on a remote LLM, most of the time is network waiting, so a higher default_concurrency_limit serves more users at once. Raise it until you hit your provider's rate limit or your memory budget. max_size caps the number of waiting requests. Beyond it, new users see an error instead of waiting forever.
If your function loads a local model on a GPU, keep the limit low. Several simultaneous generations can exhaust GPU memory.
Containerizing
A container packages the app with its dependencies. Create requirements.txt with gradio and openai, then:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
ENV GRADIO_SERVER_NAME=0.0.0.0
ENV GRADIO_SERVER_PORT=7860
EXPOSE 7860
CMD ["python", "app.py"]Build and run it, passing the key from your shell instead of baking it into the image:
docker build -t chat-app .
docker run --rm -p 7860:7860 -e OPENAI_API_KEY chat-app-e OPENAI_API_KEY with no value copies the variable from your current shell. If you forget GRADIO_SERVER_NAME=0.0.0.0, the app starts without errors but the browser cannot connect, because the server listens only on the container's loopback interface. This is the most common deployment failure.
Behind a reverse proxy
In production you normally put a reverse proxy such as Nginx in front of the app. The proxy terminates HTTPS and can serve the app under a sub-path like /chat/. Two settings matter:
- Tell Gradio its public prefix with
launch(root_path="/chat"), so that generated links and asset URLs include it. - Turn off response buffering in the proxy. Gradio streams partial replies as server-sent events, and a buffering proxy holds them back. The user sees the whole reply appear at once, or a stalled one.
location /chat/ {
proxy_pass http://127.0.0.1:7860/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
}If streaming works locally but not through the proxy, check buffering first.
Mounting inside an existing web app
If you already have a FastAPI service, you can serve the chat UI from it instead of running a second process:
import gradio as gr
from fastapi import FastAPI
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
app = FastAPI()
@app.get("/health")
def health():
return {"status": "ok"}
app = gr.mount_gradio_app(app, demo, path="/chat")Run it with uvicorn module_name:app --host 0.0.0.0 --port 7860, replacing module_name with your file name. The chat UI is at /chat, and your own routes, like /health, sit beside it. A health route is useful for load balancers.
Route 3: a Hugging Face Space
A Space is a Git repository that Hugging Face builds and runs for you. It is a good fit for long-lived public demos.
- Create a new Space on huggingface.co and choose the Gradio SDK.
- Add your
app.pyand arequirements.txtlisting the extra packages (for exampleopenai). Gradio itself is installed by the platform. - Make sure the repository
README.mdstarts with YAML metadata that names the SDK and entry file:
---
title: My Chat App
sdk: gradio
app_file: app.py
---- Open the Space's Settings and add
OPENAI_API_KEYunder secrets. Secrets reach your code as environment variables, so theOpenAI()client works unchanged. - Push to the repository. The Space rebuilds and serves the app at a stable URL.
Do not set server_name or the port yourself on a Space. The platform supplies them. Free hardware sleeps after inactivity and needs a short cold start on the next visit.
Comparing the routes
| Concern | `share=True` | Own server or container | Hugging Face Space |
|---|---|---|---|
| Setup time | Seconds | Hours | Minutes |
| Lifetime | Temporary | As long as you run it | Persistent |
| Where code runs | Your machine | Your infrastructure | Hugging Face |
| HTTPS | Provided | You configure it | Provided |
| Secrets | Your shell | Environment or secret store | Space settings |
| Cost control | Hard | Queue and proxy limits | Queue and hardware tier |
Common mistakes
- Setting
server_name="0.0.0.0"on a laptop on public Wi-Fi. This exposes the app to everyone on that network. - Committing API keys to the repository, especially for a public Space. Always use secrets.
- Leaving
max_sizeunset and letting an unbounded line of users pile up. - Testing only on
localhost, then finding that a proxy breaks streaming.
Exercise
You run your chat app in a Docker container with -p 7860:7860. The container logs show "Running on local URL: http://127.0.0.1:7860", but your browser on the host cannot load the page. What is wrong, and how do you fix it without changing the code?
Show answer
Gradio is bound to the container's loopback address (127.0.0.1), which the published port cannot reach. Make it listen on all interfaces by setting the environment variable GRADIO_SERVER_NAME=0.0.0.0, either with ENV in the Dockerfile or with docker run -e GRADIO_SERVER_NAME=0.0.0.0.
Exercise
Your app streams replies correctly at http://localhost:7860 but, behind Nginx, each answer appears all at once after a delay. Name the likely cause and the setting that fixes it.
Show answer
Nginx is buffering the streamed (server-sent event) response. Add proxy_buffering off; to the location block that proxies to Gradio, and reload Nginx.