# Command-Line Interface

Complete command-line interface for running uvicorn from the terminal.

## Imports

```python
from uvicorn.main import main
```

## Command Syntax

```bash
uvicorn [OPTIONS] APP
```

## Arguments

```bash
APP  ASGI application import string (e.g., "myapp:app")
```

The application can be specified as:
- Module and attribute: `myapp:app` (imports `app` from `myapp` module)
- Module and factory: `myapp:create_app` with `--factory` flag
- Nested attributes: `myapp.wsgi:application`

## CLI Function

```python { .api }
def main() -> None:
    """
    Main CLI entry point decorated with Click.

    Parses command-line arguments and runs the ASGI server.
    All options are passed to the run() function.

    Exit codes:
    - 0: Normal exit
    - 3: Startup failure (STARTUP_FAILURE constant)
    """
```

## Options

### Network Binding

```bash
--host TEXT
```
Bind socket to this host. (default: 127.0.0.1)

```bash
--port INTEGER
```
Bind socket to this port. (default: 8000)

```bash
--uds TEXT
```
Bind to Unix domain socket at this path.

```bash
--fd INTEGER
```
Bind to socket from this file descriptor.

### Development

```bash
--reload
```
Enable auto-reload on file changes. (default: disabled)

```bash
--reload-dir PATH
```
Set directories to watch for file changes. Can be specified multiple times. (default: current directory)

```bash
--reload-include TEXT
```
Set glob patterns to include for reload watching. Can be specified multiple times.

```bash
--reload-exclude TEXT
```
Set glob patterns to exclude from reload watching. Can be specified multiple times.

```bash
--reload-delay FLOAT
```
Delay in seconds between checking for file changes. (default: 0.25)

### Workers

```bash
--workers INTEGER
```
Number of worker processes to run. (default: 1)

### Event Loop

```bash
--loop [none|auto|asyncio|uvloop]
```
Event loop implementation. (default: auto)
- `auto`: Automatically select uvloop if available, otherwise asyncio
- `asyncio`: Use asyncio event loop
- `uvloop`: Use uvloop (requires uvloop package)
- `none`: No event loop configuration

### HTTP Protocol

```bash
--http [auto|h11|httptools]
```
HTTP protocol implementation. (default: auto)
- `auto`: Automatically select httptools if available, otherwise h11
- `h11`: Use h11 pure-Python implementation
- `httptools`: Use httptools (requires httptools package)

### WebSocket

```bash
--ws [auto|none|websockets|websockets-sansio|wsproto]
```
WebSocket protocol implementation. (default: auto)
- `auto`: Automatically select websockets if available
- `none`: Disable WebSocket support
- `websockets`: Use websockets library
- `websockets-sansio`: Use websockets sans-IO implementation
- `wsproto`: Use wsproto library

```bash
--ws-max-size INTEGER
```
Maximum WebSocket message size in bytes. (default: 16777216)

```bash
--ws-max-queue INTEGER
```
Maximum WebSocket message queue length. (default: 32)

```bash
--ws-ping-interval FLOAT
```
WebSocket ping interval in seconds. (default: 20.0)

```bash
--ws-ping-timeout FLOAT
```
WebSocket ping timeout in seconds. (default: 20.0)

```bash
--ws-per-message-deflate / --no-ws-per-message-deflate
```
Enable/disable WebSocket per-message deflate compression. (default: enabled)

### Lifespan

```bash
--lifespan [auto|on|off]
```
Lifespan event handling mode. (default: auto)
- `auto`: Enable lifespan if application supports it
- `on`: Force lifespan events (error if not supported)
- `off`: Disable lifespan events

### Interface

```bash
--interface [auto|asgi3|asgi2|wsgi]
```
Application interface type. (default: auto)
- `auto`: Automatically detect interface type
- `asgi3`: ASGI3 interface
- `asgi2`: ASGI2 interface (class-based)
- `wsgi`: WSGI interface

### Logging

```bash
--log-config PATH
```
Logging configuration file path. Supports .json, .yaml, and .ini formats.

```bash
--log-level [critical|error|warning|info|debug|trace]
```
Logging level. (default: info)

```bash
--access-log / --no-access-log
```
Enable/disable access logging. (default: enabled)

```bash
--use-colors / --no-use-colors
```
Enable/disable colored logging output. (default: auto-detect)

### Headers

```bash
--proxy-headers / --no-proxy-headers
```
Enable/disable proxy header parsing (X-Forwarded-*). (default: enabled)

```bash
--server-header / --no-server-header
```
Enable/disable Server header in responses. (default: enabled)

```bash
--date-header / --no-date-header
```
Enable/disable Date header in responses. (default: enabled)

```bash
--forwarded-allow-ips TEXT
```
Comma-separated list of IPs to trust for proxy headers. (default: 127.0.0.1)

```bash
--header TEXT
```
Add custom default header in Name:Value format. Can be specified multiple times.

### Application

```bash
--root-path TEXT
```
Set ASGI root_path for sub-mounted applications. (default: "")

```bash
--app-dir TEXT
```
Add directory to PYTHONPATH before importing application. (default: current directory)

```bash
--factory
```
Treat APP as a factory function that returns the application. (default: disabled)

### Performance

```bash
--limit-concurrency INTEGER
```
Maximum number of concurrent connections. (default: unlimited)

```bash
--backlog INTEGER
```
Socket listen backlog size. (default: 2048)

```bash
--limit-max-requests INTEGER
```
Maximum requests before worker restart. (default: unlimited)

### Timeouts

```bash
--timeout-keep-alive INTEGER
```
Keep-alive connection timeout in seconds. (default: 5)

```bash
--timeout-graceful-shutdown INTEGER
```
Graceful shutdown timeout in seconds. (default: unlimited)

```bash
--timeout-worker-healthcheck INTEGER
```
Worker health check timeout in seconds. (default: 5)

### SSL/TLS

```bash
--ssl-keyfile TEXT
```
SSL private key file path.

```bash
--ssl-certfile TEXT
```
SSL certificate file path.

```bash
--ssl-keyfile-password TEXT
```
Password for encrypted SSL private key.

```bash
--ssl-version INTEGER
```
SSL protocol version. (default: ssl.PROTOCOL_TLS_SERVER)

```bash
--ssl-cert-reqs INTEGER
```
SSL certificate requirements. (default: ssl.CERT_NONE)

```bash
--ssl-ca-certs TEXT
```
CA certificates file path for client verification.

```bash
--ssl-ciphers TEXT
```
SSL cipher configuration. (default: "TLSv1")

### Protocol-Specific

```bash
--h11-max-incomplete-event-size INTEGER
```
Maximum buffer size for h11 incomplete events in bytes.

```bash
--env-file PATH
```
Environment file (.env) to load before starting.

### Information

```bash
--version
```
Display uvicorn version and exit.

```bash
--help
```
Display help message and exit.

## Usage Examples

### Basic Usage

```bash
# Run application from myapp module
uvicorn myapp:app

# Specify host and port
uvicorn myapp:app --host 0.0.0.0 --port 8000

# Run on all interfaces
uvicorn myapp:app --host 0.0.0.0
```

### Development Mode

```bash
# Enable auto-reload
uvicorn myapp:app --reload

# Watch specific directories
uvicorn myapp:app --reload --reload-dir ./src --reload-dir ./lib

# Watch specific file patterns
uvicorn myapp:app --reload \
  --reload-include "*.py" \
  --reload-include "*.yaml" \
  --reload-exclude "*.pyc"

# Enable debug logging
uvicorn myapp:app --reload --log-level debug

# Enable trace logging
uvicorn myapp:app --reload --log-level trace
```

### Production Mode

```bash
# Run with multiple workers
uvicorn myapp:app --host 0.0.0.0 --port 8000 --workers 4

# Production configuration
uvicorn myapp:app \
  --host 0.0.0.0 \
  --port 8000 \
  --workers 4 \
  --limit-concurrency 1000 \
  --limit-max-requests 10000 \
  --timeout-keep-alive 5 \
  --timeout-graceful-shutdown 30 \
  --access-log

# Disable access logs for performance
uvicorn myapp:app --workers 4 --no-access-log
```

### SSL/TLS

```bash
# Enable HTTPS
uvicorn myapp:app \
  --host 0.0.0.0 \
  --port 443 \
  --ssl-keyfile /path/to/key.pem \
  --ssl-certfile /path/to/cert.pem

# HTTPS with client verification
uvicorn myapp:app \
  --ssl-keyfile /path/to/key.pem \
  --ssl-certfile /path/to/cert.pem \
  --ssl-ca-certs /path/to/ca.pem \
  --ssl-cert-reqs 2
```

### Unix Domain Socket

```bash
# Bind to Unix socket
uvicorn myapp:app --uds /tmp/uvicorn.sock

# Run behind Nginx with Unix socket
uvicorn myapp:app --uds /var/run/uvicorn.sock --workers 4
```

### Protocol Selection

```bash
# Use specific HTTP protocol
uvicorn myapp:app --http h11
uvicorn myapp:app --http httptools

# Use specific WebSocket protocol
uvicorn myapp:app --ws websockets
uvicorn myapp:app --ws wsproto

# Disable WebSocket support
uvicorn myapp:app --ws none

# Use specific event loop
uvicorn myapp:app --loop uvloop
```

### Custom Headers

```bash
# Add custom default headers
uvicorn myapp:app \
  --header "X-API-Version:1.0" \
  --header "X-Server:MyAPI"

# Disable standard headers
uvicorn myapp:app --no-server-header --no-date-header
```

### Proxy Configuration

```bash
# Trust proxy headers from localhost
uvicorn myapp:app --proxy-headers --forwarded-allow-ips "127.0.0.1"

# Trust multiple proxy IPs
uvicorn myapp:app --proxy-headers \
  --forwarded-allow-ips "127.0.0.1,10.0.0.1,192.168.1.1"

# Trust proxy network
uvicorn myapp:app --proxy-headers \
  --forwarded-allow-ips "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"

# Disable proxy headers
uvicorn myapp:app --no-proxy-headers
```

### Application Mounting

```bash
# Mount application at subpath
uvicorn myapp:app --root-path /api/v1

# Add custom module directory
uvicorn myapp:app --app-dir /path/to/app

# Use factory function
uvicorn myapp:create_app --factory
```

### Logging Configuration

```bash
# Use custom logging config
uvicorn myapp:app --log-config logging.yaml

# JSON logging config
uvicorn myapp:app --log-config logging.json

# INI logging config
uvicorn myapp:app --log-config logging.ini

# Set log level
uvicorn myapp:app --log-level warning
```

### Environment Configuration

```bash
# Load environment file
uvicorn myapp:app --env-file .env

# Load production environment
uvicorn myapp:app --env-file .env.production
```

### WebSocket Configuration

```bash
# Configure WebSocket limits
uvicorn myapp:app \
  --ws-max-size 33554432 \
  --ws-max-queue 64 \
  --ws-ping-interval 30.0 \
  --ws-ping-timeout 30.0

# Disable WebSocket compression
uvicorn myapp:app --no-ws-per-message-deflate
```

### Interface Selection

```bash
# Run ASGI2 application
uvicorn myapp:App --interface asgi2

# Run WSGI application (e.g., Flask)
uvicorn myapp:app --interface wsgi

# Auto-detect interface
uvicorn myapp:app --interface auto
```

### Performance Tuning

```bash
# High-performance configuration
uvicorn myapp:app \
  --host 0.0.0.0 \
  --port 8000 \
  --workers 8 \
  --http httptools \
  --loop uvloop \
  --limit-concurrency 2000 \
  --backlog 4096 \
  --no-access-log

# Connection limiting
uvicorn myapp:app --limit-concurrency 500

# Request limiting
uvicorn myapp:app --limit-max-requests 50000
```

### Timeouts

```bash
# Configure timeouts
uvicorn myapp:app \
  --timeout-keep-alive 10 \
  --timeout-graceful-shutdown 60 \
  --timeout-worker-healthcheck 10
```

### Python Module Execution

```bash
# Run uvicorn as module
python -m uvicorn myapp:app

# With options
python -m uvicorn myapp:app --host 0.0.0.0 --port 8000 --reload
```

### Lifespan Control

```bash
# Force lifespan events
uvicorn myapp:app --lifespan on

# Disable lifespan events
uvicorn myapp:app --lifespan off

# Auto-detect lifespan support
uvicorn myapp:app --lifespan auto
```

### Complete Production Example

```bash
uvicorn myapp:app \
  --host 0.0.0.0 \
  --port 8000 \
  --workers 4 \
  --loop uvloop \
  --http httptools \
  --ws websockets \
  --proxy-headers \
  --forwarded-allow-ips "10.0.0.0/8" \
  --limit-concurrency 1000 \
  --backlog 2048 \
  --limit-max-requests 100000 \
  --timeout-keep-alive 5 \
  --timeout-graceful-shutdown 30 \
  --timeout-worker-healthcheck 10 \
  --access-log \
  --log-level info \
  --no-use-colors
```

### Complete Development Example

```bash
uvicorn myapp:app \
  --host 127.0.0.1 \
  --port 8000 \
  --reload \
  --reload-dir ./src \
  --reload-include "*.py" \
  --reload-include "*.yaml" \
  --reload-exclude "*.pyc" \
  --reload-exclude "__pycache__/*" \
  --log-level debug \
  --use-colors \
  --access-log
```

## Environment Variables

Uvicorn CLI also respects environment variables for configuration when using an env-file:

```bash
# .env file
HOST=0.0.0.0
PORT=8000
WORKERS=4
LOG_LEVEL=info
RELOAD=false
```

```bash
# Load from env file
uvicorn myapp:app --env-file .env
```

## Exit Codes

- `0`: Normal exit (server shutdown gracefully)
- `3`: Startup failure (application failed to start)

## Version Information

```bash
# Show version
uvicorn --version

# Output format:
# Running uvicorn 0.37.0 with CPython 3.11.0 on Linux
```

## Help Information

```bash
# Show help
uvicorn --help

# Show detailed help for all options
uvicorn --help
```

## Running with Gunicorn

Uvicorn can also be used as a Gunicorn worker (deprecated, use uvicorn-worker package instead):

```bash
gunicorn myapp:app -w 4 -k uvicorn.workers.UvicornWorker
```

## Docker Usage

```bash
# Dockerfile
FROM python:3.11
WORKDIR /app
COPY . .
RUN pip install uvicorn[standard]
CMD ["uvicorn", "myapp:app", "--host", "0.0.0.0", "--port", "8000"]
```

```bash
# Build and run
docker build -t myapp .
docker run -p 8000:8000 myapp
```

## Systemd Service

```ini
# /etc/systemd/system/uvicorn.service
[Unit]
Description=Uvicorn ASGI Server
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/usr/local/bin/uvicorn myapp:app \
  --host 0.0.0.0 \
  --port 8000 \
  --workers 4
Restart=always

[Install]
WantedBy=multi-user.target
```

```bash
# Enable and start service
sudo systemctl enable uvicorn
sudo systemctl start uvicorn
```
