Telegram is one of the most powerful platforms for building automated bots, notification gateways, and media-processing applications. However, developers who build media-heavy Telegram bots quickly encounter a frustrating roadblock: Telegram’s default public Bot API server enforces a strict 50 MB maximum upload limit and a 20 MB maximum download limit for bot requests. If your bot handles high-definition videos, large compressed archives, dataset backups, or media streaming, these cloud API limits become an immediate bottleneck.
Fortunately, Telegram open-sourced their core C++ Bot API server (tdlib/telegram-bot-api). By self-hosting this server locally via Docker, developers can completely bypass default cloud restrictions. A self-hosted Telegram Bot API server allows your bot to send and receive files up to 2 GB in size, download media directly to your local file system, run with significantly lower API request latency, and eliminate intermediate network throttles.
In this step-by-step tutorial, you will learn how to deploy the official Telegram Bot API server using Docker Compose in 2026, configure Python bot frameworks (such as Aiogram 3 and Python-Telegram-Bot) to use your local server, verify 2 GB uploads, and secure your production environment.
Self-hosting Telegram's C++ Bot API server in Docker unlocks 2 GB file handling, local file path downloads, and lower network latency. To launch it, run the telegram-bot-api container with your TELEGRAM_API_ID and TELEGRAM_API_HASH from my.telegram.org, pass the --local flag, and direct your Python bot's base URL to http://localhost:8081. Explore top developer resources in the Telekit Tech & Developer Directory.
Public Bot API vs. Self-Hosted Telegram Bot API Server
Understanding why you should self-host Telegram's Bot API server boils down to architectural flexibility and file limits. When your bot sends HTTP requests to https://api.telegram.org, every payload passes through Telegram's shared cloud proxies. When you run a local instance, your bot communicates directly with your self-hosted TDLib proxy, which talks directly to Telegram’s MTProto core servers.
Prerequisites for Deploying Telegram Bot API
Before launching your containerized server, ensure you have the following prerequisites ready:
- Linux VPS or Server: Ubuntu 22.04/24.04 LTS or Debian 12 with Docker and Docker Compose installed.
- Telegram App Credentials: Your personal
TELEGRAM_API_IDandTELEGRAM_API_HASH. These can be generated for free by logging into my.telegram.org. - Telegram Bot Token: A valid bot token generated via @BotFather.
- Minimum Server Hardware: 1 CPU Core, 2 GB RAM, and sufficient NVMe storage for handling buffered media files.
Step 1: Obtain Telegram API ID and API Hash
The self-hosted Telegram Bot API server connects directly to Telegram's backend datacenters. To authenticate your local server instance with Telegram's core network, you must obtain an application ID and hash.
- Navigate to my.telegram.org and log in using your personal Telegram phone number.
- Select API Development Tools.
- Fill in the short application registration form (App title, Short name, URL).
- Copy down your
App api_id(an integer like28475923) andApp api_hash(a 32-character hexadecimal string likea1b2c3d4e5f67890123456789abcdef0).
Step 2: Deploying Telegram Bot API Server via Docker Compose
The official Docker image for the Telegram Bot API server is maintained under aiogram/telegram-bot-api and tdlib/telegram-bot-api. We will create a dedicated directory on your VPS, store our environment configuration, and spin up the service in Docker.
Run the following terminal commands to prepare your project folder:
mkdir -p ~/telegram-bot-server/{data,config}
cd ~/telegram-bot-server
Next, create a docker-compose.yml file in the ~/telegram-bot-server/ folder:
version: '3.8'
services:
telegram-bot-api:
image: aiogram/telegram-bot-api:latest
container_name: telegram_bot_api_server
restart: unless-stopped
environment:
- TELEGRAM_API_ID=YOUR_API_ID_HERE
- TELEGRAM_API_HASH=YOUR_API_HASH_HERE
- TELEGRAM_LOCAL=true
ports:
- "8081:8081"
volumes:
- ./data:/var/lib/telegram-bot-api
command: >
--api-id=${TELEGRAM_API_ID}
--api-hash=${TELEGRAM_API_HASH}
--local
--dir=/var/lib/telegram-bot-api
--http-port=8081
Create an .env file alongside docker-compose.yml to securely store your credentials:
TELEGRAM_API_ID=28475923 TELEGRAM_API_HASH=a1b2c3d4e5f67890123456789abcdef0
Now start the container in detached mode and verify that the local server is running properly:
docker compose up -d docker logs -f telegram_bot_api_server
You should see log output confirming that the local HTTP server has bound to port 8081 and successfully established a connection with Telegram datacenters.
Step 3: Configuring Python Bot Frameworks for Local API Server
To start routing your bot's API calls to your local server instead of https://api.telegram.org, you must update the bot client initialization code. Below are examples using Aiogram 3 and Python-Telegram-Bot.
Option A: Aiogram 3 (Python)
In Aiogram 3, you override the TelegramAPIServer base URL when initializing the Bot instance:
import asyncio
from aiogram import Bot, Dispatcher, types
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
from aiogram.types import FSInputFile
# Configure Local Server Session
session = AiohttpSession(
api=TelegramAPIServer.from_base("http://localhost:8081", is_local=True)
)
BOT_TOKEN = "1234567890:ABCdefGHIjklMNOpqrsTUVwxyZ"
bot = Bot(token=BOT_TOKEN, session=session)
dp = Dispatcher()
@dp.message()
def handle_docs(message: types.Message):
# Upload large files up to 2 GB seamlessly!
large_file = FSInputFile("/path/to/large_video.mp4")
yield from message.answer_document(large_file, caption="Uploaded via Local Bot API!")
async def main():
print("Bot starting with Local Telegram Bot API Server...")
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
Option B: Python-Telegram-Bot
If you are using the python-telegram-bot library, configure the custom base_url and base_file_url in your application builder:
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hello from self-hosted Telegram Bot API!")
if __name__ == '__main__':
LOCAL_SERVER = "http://localhost:8081/bot{token}/{method}"
LOCAL_FILE_SERVER = "http://localhost:8081/file/bot{token}/{path}"
app = ApplicationBuilder() .token("YOUR_BOT_TOKEN") .base_url(LOCAL_SERVER) .base_file_url(LOCAL_FILE_SERVER) .local_mode(True) .build()
app.add_handler(CommandHandler("start", start))
app.run_polling()
Step 4: Testing & Verifying 2 GB Uploads with Terminal Commands
Before putting your bot into production, verify that your local container responds to API requests using curl from your terminal.
First, test the basic /getMe endpoint against port 8081:
curl -s http://localhost:8081/botYOUR_BOT_TOKEN/getMe | jq .
Next, test uploading a 500 MB file (which would normally be rejected with a 413 Payload Too Large error on the cloud API):
# Create a 250MB test dummy file dd if=/dev/urandom of=large_test_file.zip bs=1M count=250 # Send the file via local server curl -F chat_id="YOUR_CHAT_ID" -F document=@large_test_file.zip -F caption="Test 250MB upload via local API" http://localhost:8081/botYOUR_BOT_TOKEN/sendDocument
If configured correctly, Telegram will accept the 250 MB file payload instantly and transmit it to your specified chat ID without throwing size limits.
Step 5: Production Hardening, Nginx Reverse Proxy & Security
If your bot is deployed on a remote VPS and receives incoming webhooks from Telegram, or if multiple backend services connect to your local Bot API server, you should harden the setup with Nginx and SSL encryption.
Create an Nginx configuration file at /etc/nginx/sites-available/telegram-bot-api:
server {
listen 80;
server_name bot-api.yourdomain.com;
client_max_body_size 2000M; # Allow up to 2GB uploads
location / {
proxy_pass http://127.0.0.1:8081;
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_set_header X-Forwarded-Proto $scheme;
# Increase proxy timeouts for large file transfers
proxy_connect_timeout 600s;
proxy_send_timeout 600s;
proxy_read_timeout 600s;
}
}
Enable the Nginx block and secure it with a free SSL certificate via Let's Encrypt Certbot:
sudo ln -s /etc/nginx/sites-available/telegram-bot-api /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx sudo certbot --nginx -d bot-api.yourdomain.com
Finally, restrict external access to port 8081 using UFW so that only localhost or your Nginx reverse proxy can communicate directly with the container:
sudo ufw deny 8081/tcp sudo ufw allow 80/tcp sudo ufw allow 443/tcp sudo ufw status
Frequently Asked Questions (FAQ)
Why does the default Telegram Bot API restrict file uploads to 50 MB?
Telegram enforces a 50 MB upload limit on their public api.telegram.org servers to prevent millions of bots from abusing shared cloud bandwidth and memory. Self-hosting shifts the file buffering load to your own infrastructure, allowing Telegram to grant full 2 GB file transfer permissions.
Is self-hosting the Telegram Bot API server completely free?
Yes. The C++ Telegram Bot API server source code is 100% open source under the Boost Software License 1.0. There are no fees or commercial licenses required to run it.
Can I download received user files directly to my server's hard drive?
Yes! When running with the --local flag enabled, file download requests return direct local file paths (e.g., /var/lib/telegram-bot-api/bot123.../documents/file.pdf), eliminating the need to download files over HTTP.
What hardware specifications are required for running the Bot API in Docker?
A basic Linux VPS with 1 CPU core and 2 GB RAM is sufficient for standard bots. If your bot actively processes multiple simultaneous 2 GB file transfers, allocate at least 4 GB RAM and fast NVMe storage for disk buffering.
Do I need to change anything in my BotFather settings?
No changes are required in @BotFather. You use the exact same bot token; only the base request URL in your Python code is changed from https://api.telegram.org to your local server address.
Conclusion
Self-hosting the official Telegram Bot API server with Docker is the ultimate upgrade for Python developers building high-capacity bots. By removing the 50 MB cloud limit and enabling 2 GB file uploads, local file system streaming, and ultra-fast webhook dispatches, your Telegram automation can handle heavy media workflows with ease. Ready to discover more advanced Telegram automation strategies and developer tools? Check out the Telekit Tech Directory and browse our curated list of Top Telegram Bots today!